preg_quote

(PHP 3 >= 3.0.9, PHP 4, PHP 5)

preg_quote -- 转义正则表达式字符

说明

string preg_quote ( string str [, string delimiter] )

preg_quote()str 为参数并给其中每个属于正则表达式语法的字符前面加上一个反斜线。如果你需要以动态生成的字符串作为模式去匹配则可以用此函数转义其中可能包含的特殊字符。

如果提供了可选参数 delimiter,该字符也将被转义。可以用来转义 PCRE 函数所需要的定界符,最常用的定界符是斜线 /。

正则表达式的特殊字符包括:. \\ + * ? [ ^ ] $ ( ) { } = ! < > | :

例子 1. preg_quote() 例子

<?php
$keywords
= "$40 for a g3/400";
$keywords = preg_quote ($keywords, "/");
echo
$keywords; // returns \$40 for a g3\/400
?>

例子 2. 给某文本中的一个单词加上斜体标记

<?php
// 本例中,preg_quote($word) 用来使星号不在正则表达式中
// 具有特殊含义。

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


add a note add a note User Contributed Notes
php dot net at sharpdreams dot com
25-Jul-2005 10:34
Re (2) rdude at fuzzelfish dot com:

In case anyone else missed it, you do NOT have to use / as your preg escape character. You can use any two matching characters.
me@localhost
30-Mar-2005 02:51
Re rdude at fuzzelfish dot com:

You can specify a delimiter that will be escaped, too.
preg_quote('abc/', '/') does the job.
rdude at fuzzelfish dot com
17-Feb-2005 12:35
Another character that preg_quote will not escape is the all important "/" character. You will need to convert "/" into "\/" yourself. For example, this code does not work:

<?
 $TEXT
= preg_replace('/[' . preg_quote('abc/') . ']/', '', $TEXT);
?>

However, this does:

<?
 $TEXT
= preg_replace('/[' . preg_quote('abc') . '\/]/', '', $TEXT);
?>
mina86 at tlen dot pl
26-Dec-2003 07:02
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
16-Jul-2003 08:12
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);