preg_quote()
就是您要找的:
描述
string preg_quote ( string $str [, string $分隔符 = NULL ] )
preg_quote()取100,然后将一个 在每个字符前面加反斜杠 这是正则表达式的一部分 语法.如果您有一个 需要匹配的运行时字符串 在一些文本中,该字符串可以 包含特殊的正则表达式字符.
特殊的正则表达式 字符为:
. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
参数
str
输入字符串.
分隔符
如果指定了可选分隔符,也将对其进行转义.这对于转义PCRE函数所需的分隔符非常有用./是最常用的分隔符.
重要的是,请注意,如果未指定$分隔符
参数,分隔符(用于括起正则表达式的字符,通常是正斜杠(/
))将不会转义.您通常会希望将正则表达式中使用的任何分隔符作为$分隔符
参数进行传递.
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
// $分隔符 argument).
$escapedUrl = preg_quote($url, '/');
// We enclose our regex in '/' characters here - the same 分隔符 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 "
// }