|
preg_quote
Quote regular expression characters
(PHP 4, PHP 5)
Example 1721. preg_quote() example<?php Example 1722. Italicizing a word within some text<?php Code Examples / Notes » preg_quotemina86
Re: adrian holovaty You must also escape '#' character. Next thing is that there is more then one whitespace character (a space).. Also IMO the name preg_quote_white() won't tell what the new function does so we could rename it. And finally, we should also add $delimiter: <?php function preg_xquote($a, $delimiter = null) { if ($delimiter) { return preg_replace('/[\s#]/', '\\\0', preg_quote($a, substr("$delimiter", 0, 1))); } else { return preg_replace('/[\s#]/', '\\\0', preg_quote($a)); } } ?> adrian holovaty
Note that if you've used the "x" pattern modifier in your regex, you'll want to make sure you escape any whitespace in your string that you *want* the pattern to match. A simplistic example: $phrase = 'a test'; // note the space $textbody = 'this is a test'; // Does not match: preg_match('/' . preg_quote($phrase) . '$/x', $textbody); function preg_quote_white($a) { $a = preg_quote($a); $a = str_replace(' ', '\ ', $a); return $a; } // Does match: preg_match('/' . preg_quote_white($phrase) . '$/x', $textbody); chad
If you are placing your quoted string within []'s, make sure you also escape the dash (-) character manually. preg_match("/^[A-Za-z\d" . preg_quote('!@#$%^&*()-_=+\|[]{};:/?.><', '/') . "]{8,32}$/", $password) The above will try to match the characters ')' through '_' whatever those are. So use the below expression: preg_match("/^[A-Za-z\d" . preg_quote('!@#$%^&*()_=+\|[]{};:/?.><', '/') . "\-]{8,32}$/", $password) Yes, I know I can use \w in place of A-Za-z, but I wanted to illustrate my point better :) |