将正则表达式翻译成 PHP
translate regex to PHP
我正在努力将此功能移植到 PHP。
SomeString.replace(/([.*+?^=!:${}()|\[\]\/\])/g, "\");
老实说,我什至不知道它到底是做什么的。
我尝试至少使用带有 preg_replace
的表达式
但是得到了
preg_match(): Compilation failed: missing terminating ] for character class at offset 25
当使用类似
的东西时
preg_match('/([.*+?^=!:${}()|\[\]\/\])/', $string, $matches);
您可以使用:
preg_match('#([.*+?^=!:${}()|\[\]/\\])#', $string, $matches);
您的错误是在您的正则表达式中使用 \
而不是 \\
。匹配反斜杠需要双重转义。一个 \
用于 PHP,另一个 \
用于 PCRE 引擎。
javascript函数.replace
被preg_replace
翻译成php,所以:
SomeString.replace(/([.*+?^=!:${}()|\[\]\/\])/g, "\");
变成:
$SomeString = preg_replace('~([.*+?^=!:${}()|\[\]/\\])~', "\\", $SomeString);
这将单独替换字符 class 中的特殊字符,但已转义。
除此之外,您遇到的错误是由于您尝试 preg_match 时字符的双重转义,您必须双重转义。
preg_match('/([.*+?^=!:${}()|\[\]\/\\])/', $string, $matches);
// | ^^^^^ double-double escape the backslash
// ^ no needs to double escape here
我正在努力将此功能移植到 PHP。
SomeString.replace(/([.*+?^=!:${}()|\[\]\/\])/g, "\");
老实说,我什至不知道它到底是做什么的。
我尝试至少使用带有 preg_replace
的表达式
但是得到了
preg_match(): Compilation failed: missing terminating ] for character class at offset 25
当使用类似
的东西时preg_match('/([.*+?^=!:${}()|\[\]\/\])/', $string, $matches);
您可以使用:
preg_match('#([.*+?^=!:${}()|\[\]/\\])#', $string, $matches);
您的错误是在您的正则表达式中使用 \
而不是 \\
。匹配反斜杠需要双重转义。一个 \
用于 PHP,另一个 \
用于 PCRE 引擎。
javascript函数.replace
被preg_replace
翻译成php,所以:
SomeString.replace(/([.*+?^=!:${}()|\[\]\/\])/g, "\");
变成:
$SomeString = preg_replace('~([.*+?^=!:${}()|\[\]/\\])~', "\\", $SomeString);
这将单独替换字符 class 中的特殊字符,但已转义。
除此之外,您遇到的错误是由于您尝试 preg_match 时字符的双重转义,您必须双重转义。
preg_match('/([.*+?^=!:${}()|\[\]\/\\])/', $string, $matches);
// | ^^^^^ double-double escape the backslash
// ^ no needs to double escape here