问题描述
<?php
function pregForPreg($value)
{
$value = preg_replace(array('#\(#', '#\)#', '#\+#', '#\?#', '#\*#', '#\##', '#\[#', '#\]#', '#\&#', '#\/#', '#\$#', '#\\\\#'), array('\(', '\)', '\+', '\?', '\*', '\#', '\[', '\]', '\&', '\/', '\\\$', '\\\\'), $value);
return $value;
}
$var = "TI - Yeah U Know [OFFCIAL VIDEO] [TAKERS] [w\LYRICS]";
$var = pregForPreg($var);
//$var is now:
// TI - Yeah U Know \[OFFCIAL VIDEO\] \[TAKERS\] \[w\LYRICS\]
$var = preg_replace("#" . $var . "#isU", 'test', $var);
echo $var;
我收到一个错误:*警告:preg_replace():编译失败:PCRE 不支持 test.php 中偏移 50 处的 \L、\l、\N、\U 或 \ustrong> 在第 13 行.*
And I get an error: *Warning: preg_replace(): Compilation failed: PCRE does not support \L, \l, \N, \U, or \u at offset 50 in test.php on line 13.*
如何制作正确的函数pregForPreg?
How to make a correct function pregForPreg?
推荐答案
您似乎想转义特殊的正则表达式字符.这个函数已经存在,叫做preg_quote()
.
You get the error, because you don't escape \
properly:
TI - Yeah U Know \[OFFCIAL VIDEO\] \[TAKERS\] \[w\LYRICS\]
// this is not escaped ------^
and \L
has special meaning in Perl regular expression:
but is not supported in PHP's PCRE (Perl Differences):
不支持以下 Perl 转义序列:\l、\u、\L、\U
.事实上,这些是由 Perl 的一般字符串处理实现的,而不是其模式匹配引擎的一部分.
更新:
显然,您不能将转义版本用作值和模式,因为在模式中 \[
将被视为 [
而在值 中\[
是字面意思.您必须将转义的字符串存储在一个新变量中:
Obviously, you cannot use the escaped version as value and as pattern, because in the pattern \[
will be treated as [
and but in the value \[
is taken literally. You have to store the escaped string in a new variable:
$var = "TI - Yeah U Know [OFFCIAL VIDEO] [TAKERS] [w\LYRICS]";
$escaped = preg_quote($var);
echo $escaped . PHP_EOL;
// prints "TI - Yeah U Know \[OFFCIAL VIDEO\] \[TAKERS\] \[w\\LYRICS\]"
$var = preg_replace('#' . $escaped . '#isU', 'test', $var);
echo $var;
// prints test
或更简单:
$var = preg_replace('#' . preg_quote($var) . '#isU', 'test', $var);
旁注:如果你真的想在字符串中匹配 \[
,正则表达式应该是 \\\\\[
.你看,它会变得很丑.
Side note: If you really wanted to match \[
in a string, the regular expression would be \\\\\[
. You see, it can get quite ugly.
这篇关于PHP PCRE 错误 preg_replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!