PHP PCRE 错误 preg_replace [英] PHP PCRE error preg_replace

查看:59
本文介绍了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;

我收到一个错误:*警告: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().

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:

TI - Yeah U Know \[OFFCIAL VIDEO\] \[TAKERS\] \[w\LYRICS\]
//                   this is not escaped   ------^

\L 在 Perl 正则表达式中具有特殊意义:

and \L has special meaning in Perl regular expression:

\L 小写直到 \E

\L Lowercase until \E

但在 PHP 的 PCRE 中不受支持(Perl差异):

but is not supported in PHP's PCRE (Perl Differences):

不支持以下 Perl 转义序列:\l、\u、\L、\U.事实上,这些是由 Perl 的一般字符串处理实现的,而不是其模式匹配引擎的一部分.

The following Perl escape sequences are not supported: \l, \u, \L, \U. In fact these are implemented by Perl's general string-handling and are not part of its pattern matching engine.

更新:

显然,您不能将转义版本用作值和模式,因为在模式中 \[ 将被视为 [ 而在值 中\[ 是字面意思.您必须将转义的字符串存储在一个新变量中:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆