将正则表达式转换为PHP

时间:2015-02-12 18:42:46

标签: javascript php regex replace preg-replace

我正在努力将此功能移植到PHP。

SomeString.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");

说实话,我甚至不知道它究竟是做什么的。 我尝试至少使用preg_replace的表达式 但得到了

  

preg_match():编译失败:对于偏移量为25的字符类缺少终止]

使用

之类的东西
preg_match('/([.*+?^=!:${}()|\\[\\]\\/\\])/', $string, $matches);

2 个答案:

答案 0 :(得分:5)

javascript函数.replacepreg_replace在php中翻译,所以:

SomeString.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");

变为:

$SomeString = preg_replace('~([.*+?^=!:${}()|\[\]/\\\\])~', "\\\\$1", $SomeString);

这将自行替换角色类中的特殊字符,但会进行转义。

除此之外,您遇到的错误是由于您尝试使用preg_match时角色的双重逃逸,您必须双重转义。

preg_match('/([.*+?^=!:${}()|\[\]\/\\\\])/', $string, $matches);
//                           |     ^^^^^ double-double escape the backslash
//                           ^ no needs to double escape here

答案 1 :(得分:4)

您可以使用:

preg_match('#([.*+?^=!:${}()|\[\]/\\\\])#', $string, $matches);

您的错误是在正则表达式中使用\\而不是\\\\。匹配反斜杠需要双重转义。一个\\用于PHP,另一个\\用于PCRE引擎。