preg_quote() is what you are looking for:
Description
string preg_quote ( string $str [, string $delimiter = NULL ] )preg_quote() takes
strand puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.The special regular expression characters are:
. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -Parameters
str
The input string.
delimiter
If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.
Importantly, note that if the $delimiter argument is not specified, the delimiter - the character used to enclose your regex, commonly a forward slash (/) - will not be escaped. You will usually want to pass whatever delimiter you are using with your regex as the $delimiter argument.
Example - using preg_match to find occurrences of a given URL surrounded by whitespace:
$url = 'http://stackoverflow.com/questions?sort=newest';
// preg_quote escapes the dot, question mark and equals sign in the URL (by
// default) as well as all the forward slashes (because we pass '/' as the
// $delimiter argument).
$escapedUrl = preg_quote($url, '/');
// We enclose our regex in '/' characters here - the same delimiter we passed
// to preg_quote
$regex = '/\s' . $escapedUrl . '\s/';
// $regex is now: /\shttp\:\/\/stackoverflow\.com\/questions\?sort\=newest\s/
$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";
preg_match($regex, $haystack, $matches);
var_dump($matches);
// array(1) {
// [0]=>
// string(48) " http://stackoverflow.com/questions?sort=newest "
// }
Answer from Tom Haigh on Stack Overflowpreg_quote() is what you are looking for:
Description
string preg_quote ( string $str [, string $delimiter = NULL ] )preg_quote() takes
strand puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.The special regular expression characters are:
. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -Parameters
str
The input string.
delimiter
If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.
Importantly, note that if the $delimiter argument is not specified, the delimiter - the character used to enclose your regex, commonly a forward slash (/) - will not be escaped. You will usually want to pass whatever delimiter you are using with your regex as the $delimiter argument.
Example - using preg_match to find occurrences of a given URL surrounded by whitespace:
$url = 'http://stackoverflow.com/questions?sort=newest';
// preg_quote escapes the dot, question mark and equals sign in the URL (by
// default) as well as all the forward slashes (because we pass '/' as the
// $delimiter argument).
$escapedUrl = preg_quote($url, '/');
// We enclose our regex in '/' characters here - the same delimiter we passed
// to preg_quote
$regex = '/\s' . $escapedUrl . '\s/';
// $regex is now: /\shttp\:\/\/stackoverflow\.com\/questions\?sort\=newest\s/
$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";
preg_match($regex, $haystack, $matches);
var_dump($matches);
// array(1) {
// [0]=>
// string(48) " http://stackoverflow.com/questions?sort=newest "
// }
It would be much safer to use Prepared Patterns from T-Regx (i'm the author of the library):
$url = 'http://stackoverflow.com/questions?sort=newest';
$pattern = Pattern::inject('\s@\s', [$url]);
// ↑ $url is quoted
then perform normal match:
$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";
$matcher = pattern->match($haystack);
foreach ($matcher as $match) {
}
you can even use it with preg_match():
preg_match($pattern, 'foo', $matches);
preg_quote
From the manual:
puts a backslash in front of every character that is part of the regular expression syntax
You can also pass the delimiter as the second parameter and it will also be escaped. However, if you're using # as your delimiter, then there's no need to escape /
You must use the preg_quote function:
preg_quote ( string $str [, string $delimiter = NULL ] )
Example of a $keyword that must match as a whole word:
$pattern = '/\b' . preg_quote($keyword, '/') . '\b/';
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.
< and > aren't meta characters is most contexts.
However they are used as such for:
- named capture groups
(?P<name>) - 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.
In many regex implementations, the following rules apply:
Meta characters inside a character class are:
^(negation)-(range)](end of the class)\(escape char)
So these should all be escaped. There are some corner cases though:
-needs no escaping if placed at the very start, or end of the class ([abc-]or[-abc]). In quite a few regex implementations, it also needs no escaping when placed directly after a range ([a-c-abc]) or short-hand character class ([\w-abc]). This is what you observed^needs no escaping when it's not at the start of the class:[^a]means any char excepta, and[a^]matches eitheraor^, which equals:[\^a]]needs no escaping if it's the only character in the class:[]]matches the char]
[\w.-]
- the
.usually means any character but between[]has no special meaning -between[]indicates a range unless if it's escaped or either first or last character between[]
// PHP 5.4.1
// Either three or four \ can be used to match a '\'.
echo preg_match( '/\\\/', '\\' ); // 1
echo preg_match( '/\\\\/', '\\' ); // 1
// Match two backslashes `\\`.
echo preg_match( '/\\\\\\/', '\\\\' ); // Warning: No ending delimiter '/' found
echo preg_match( '/\\\\\\\/', '\\\\' ); // 1
echo preg_match( '/\\\\\\\\/', '\\\\' ); // 1
// Match one backslash using a character class.
echo preg_match( '/[\\]/', '\\' ); // 0
echo preg_match( '/[\\\]/', '\\' ); // 1
echo preg_match( '/[\\\\]/', '\\' ); // 1
When using three backslashes to match a '\' the pattern below is interpreted as match a '\' followed by an 's'.
echo preg_match( '/\\\\s/', '\\ ' ); // 0
echo preg_match( '/\\\\s/', '\\s' ); // 1
When using four backslashes to match a '\' the pattern below is interpreted as match a '\' followed by a space character.
echo preg_match( '/\\\\\s/', '\\ ' ); // 1
echo preg_match( '/\\\\\s/', '\\s' ); // 0
The same applies if inside a character class.
echo preg_match( '/[\\\\s]/', ' ' ); // 0
echo preg_match( '/[\\\\\s]/', ' ' ); // 1
None of the above results are affected by enclosing the strings in double instead of single quotes.
Conclusions:
Whether inside or outside a bracketed character class, a literal backslash can be matched using just three backslashes '\\\' unless the next character in the pattern is also backslashed, in which case the literal backslash must be matched using four backslashes.
Recommendation:
Always use four backslashes '\\\\' in a regex pattern when seeking to match a backslash.
Escape sequences.
To avoid this kind of unclear code you can use \x5c Like this :)
echo preg_replace( '/\x5c\w+\.php$/i', '<b>${0}</b>', __FILE__ );
Why not simply use preg_quote?
I believe it's just because of the order you're putting the chars in the array. Try this:
$regex_chars = array('\\' , '[' , '^', '$' , '.' , '|' ,
'?' , '*' , '+' , '(' , ')');
$regex_chars_escaped = array( '\\\\ ' ,'\[ ', '\^ ', '\& ' ,
'\. ' , '\| ' , '\? ' , '\* ' , '\+ ' , '\( ' , '\)');
And you should get the expected output. Check the 'potential gotchas' section in the str_replace function spec