This question already has an answer here:
这个问题已经有了答案:
- Is there a PHP function that can escape regex patterns before they are applied? 1 answer
- 是否有一个PHP函数可以在应用regex模式之前转义它们?1回答
I wrote the following code (yes it does work) and was wondering why I don't need to escape the '<' and '>' characters inside the pattern since they are considered 'special' characters by the php manual.
我编写了以下代码(是的,它确实可以工作),我想知道为什么不需要在模式中转义“<”和“>”字符,因为php手册认为它们是“特殊”字符。
http://www.php.net/manual/en/function.preg-quote.php
http://www.php.net/manual/en/function.preg-quote.php
var_dump(preg_match('/<[A-Za-z][A-Za-z0-9]*>/', "<html>", $matches));
echo "<pre>";
var_dump(htmlentities($matches[0]));
echo "</pre>";
output:
输出:
int(1)
string(12) "<html>"
2 个解决方案
#1
15
Only the characters listed on this page need to be escaped in PHP regex matching/replacing.
只需要在PHP regex匹配/替换中转义此页面中列出的字符。
While <
and >
can act as delimiter, it doesn't need to be escaped in the given example because you already have /
(slash) acting as a delimiter.
虽然 <和> 可以作为分隔符,但是在给定的示例中不需要转义,因为已经有/(斜杠)作为分隔符。
Referring to the link in question
指的是相关的链接
The
preg_quote()
function may be used to escape a string for injection into a pattern and its optional second parameter may be used to specify the delimiter to be escaped.preg_quote()函数可用于将字符串转义到模式中,其可选的第二个参数可用于指定要转义的分隔符。
#2
3
<
and >
aren't meta characters is most contexts.
<和> 不是元字符是大多数上下文。
However they are used as such for:
然而,它们被用于:
- named capture groups
(?P<name>)
- 名叫捕捉组(? P <名称> )
- lookbehind assertions
(?<=...)
- 向后插入断言(? < =…)
So that's why preg_quote
plays it safe and escapes them. It's arguably redundant, since escaping (
and ?
would be sufficient. But it doesn't hurt either.
这就是为什么preg_quote将其置于安全的位置,并避开它们。它可以说是多余的,因为转义(和?就足够了。但它也不疼。
#1
15
Only the characters listed on this page need to be escaped in PHP regex matching/replacing.
只需要在PHP regex匹配/替换中转义此页面中列出的字符。
While <
and >
can act as delimiter, it doesn't need to be escaped in the given example because you already have /
(slash) acting as a delimiter.
虽然 <和> 可以作为分隔符,但是在给定的示例中不需要转义,因为已经有/(斜杠)作为分隔符。
Referring to the link in question
指的是相关的链接
The
preg_quote()
function may be used to escape a string for injection into a pattern and its optional second parameter may be used to specify the delimiter to be escaped.preg_quote()函数可用于将字符串转义到模式中,其可选的第二个参数可用于指定要转义的分隔符。
#2
3
<
and >
aren't meta characters is most contexts.
<和> 不是元字符是大多数上下文。
However they are used as such for:
然而,它们被用于:
- named capture groups
(?P<name>)
- 名叫捕捉组(? P <名称> )
- lookbehind assertions
(?<=...)
- 向后插入断言(? < =…)
So that's why preg_quote
plays it safe and escapes them. It's arguably redundant, since escaping (
and ?
would be sufficient. But it doesn't hurt either.
这就是为什么preg_quote将其置于安全的位置,并避开它们。它可以说是多余的,因为转义(和?就足够了。但它也不疼。