Php regex escapes special characters

I wrote the following code (yes, it works) and wondered why I do not need to hide the '<' and '>' inside the template, since they are considered special characters in the php manual.

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>"; 

exit:

 int(1) string(12) "<html>" 
+7
source share
2 answers

Only the characters listed on this page should be escaped according to the repetition / replacement of PHP.

Although < and > can act as delimiter , in this example it does not need to be escaped because you already have / (slash) acting as delimiter .

Referring to the corresponding link

The preg_quote() function can be used to remove the string for injection into the template, and the optional second parameter can be used to specify the delimiter to be escaped.

+15
source

< and > are not metacharacters, these are most contexts.

However, they are used as such for:

  • named capture groups (?P<name>)
  • lookbehind statements (?<=...)

So why does preg_quote play safe and slip away from them. This is perhaps redundant, as avoiding ( and ? Would be enough. But that won't hurt either.

+3
source

All Articles