一位客户报告了一个错误,我已经追踪到了这个代码,但我不知道它出了什么问题:
$source = "This is a test.'n'n-- a <span style='color:red'>red word</span>!'n'n- a red word!'n'n";
//$find = "- a red word!"; // This one works!
$find = "- a <span style='color:red'>red word</span>!"; // This one doesn't...
$replace = "• a <span style='color:red'>red word</span>!";
$pattern = '/^' . preg_quote($find) . '$/';
$results = preg_replace($pattern, $replace, $source);
die ("Results: " . serialize($results));
我已经包含了一个$find
有效与$find
无效的示例。知道为什么未注释的$find
不起作用吗?
(注意:我实际上并没有试图解析HTML,搜索只是一个示例,所以我不需要对方法进行更正)
preg_quote
无法转义</span>
中的斜杠字符,这使模式无效。preg_quote
允许定义模式的分隔符:
$pattern = '/^' . preg_quote($find, '/') . '$/';
您必须移除锚点(^
$
),因为您试图匹配的只是一个子字符串,而不是所有字符串。
$pattern = '~' . preg_quote($find) . '~';
preg_quote
只转义特殊的正则表达式字符,这些字符是:. ' + * ? [ ^ ] $ ( ) { } = ! < > | : -
。因为正斜杠不是正则表达式的特殊字符,所以在像这样的模式中,必须使用不同的分隔符,比如冒号|
$pattern = '/' . preg_quote($find) . '/';
或者向preg_quote
函数提供反斜杠分隔符作为第二个参数,如
$pattern = '/' . preg_quote($find, '/') . '$/';
来自关于preg_quote
函数的PHP文档(第二个参数的描述):
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.
并且去掉^
和$
,正如已经建议的那样——您没有匹配整个字符串。