PHP PCRE 错误 preg_replace
<?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;
我收到一个错误: *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?
<?php
function pregForPreg($value)
{
$value = preg_replace(array('#\(#', '#\)#', '#\+#', '#\?#', '#\*#', '#\##', '#\[#', '#\]#', '#\', '#\/#', '#\$#', '#\\\\#'), array('\(', '\)', '\+', '\?', '\*', '\#', '\[', '\]', '\&', '\/', '\\\
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.*
How to make a correct function pregForPreg?
, '\\\\'), $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;
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.*
How to make a correct function pregForPreg?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来你想转义特殊的正则表达式字符。该函数已经存在,名为
preg_quote()
。您会收到错误,因为您没有正确转义
\
:并且
\L
在 Perl 正则表达式中具有特殊含义:但PHP 的 PCRE 不支持(Perl 差异):
更新:
显然,您不能使用转义版本作为值和模式,因为在模式中
\[
将被视为[
并且值\[
按字面意思理解。您必须将转义字符串存储在新变量中:或更简单:
旁注:如果您确实想匹配字符串中的
\[
,则正则表达式将为\\\\\ [。你看,它可能会变得非常难看。
It seems you want to escape special regex characters. This function already exists and is called
preg_quote()
.You get the error, because you don't escape
\
properly:and
\L
has special meaning in Perl regular expression:but is not supported in PHP's PCRE (Perl Differences):
Update:
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:or easier:
Side note: If you really wanted to match
\[
in a string, the regular expression would be\\\\\[
. You see, it can get quite ugly.