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.
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>"
The \ is known as the escape code, which restore the original literal meaning of the following character. Similarly, * , + , ? (occurrence indicators), ^ , $ (position anchors) have special meaning in regex. You need to use an escape code to match with these characters.
An escape sequence tells the program to stop the normal operating procedure and evaluate the following characters differently. In PHP, an escape sequence starts with a backslash \ . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.
Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence. When you use braces to escape a single character, the escaped character becomes a separate token in the query. Use the backslash character to escape a single character or symbol.
The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.
Only the characters listed on this page need to be escaped in PHP regex matching/replacing.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With