Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Function Reference : Regular Expression Functions (Perl-Compatible) : preg_quote


Quote regular expression characters (PHP 4, PHP 5)
string preg_quote ( string str [, string delimiter] )

Example 1721. preg_quote() example

= '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
$keywords; // returns \$40 for a g3\/400

Example 1722. Italicizing a word within some text

// In this example, preg_quote($word) is used to keep the
// asterisks from having special meaning to the regular
// expression.

$textbody = "This book is *very* difficult to find.";
$word = "*very*";
$textbody = preg_replace ("/" . preg_quote($word) . "/",
"<i>" . $word . "</i>",

Code Examples / Notes » preg_quote


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:
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);


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 :)

Change Language

Follow Navioo On Twitter
Pattern Modifiers
Pattern Syntax
eXTReMe Tracker