PHP preg_replace()中的反向引用是不稳定的?

时间:2013-09-23 15:34:23

标签: php html regex

为了避免双引号或单引号,我使用了正则表达式反引用:

$strVal = '<div class="xclassname">Contents</div>';
$strVal = preg_replace("/([\"\'])/", "\\\\1", $strVal);

这通常给了我这个字符串(多年):

"<div class=\"xclassname\">Contents</div>"

双引号在C ++风格中正确转义。

但今天我的PHP 5.5.3给了我这个结果:

"<div class=\1xclassname\1>Contents</div>"

将双引号替换为bad \ 1字符串。

现在我必须使用它:

$strVal = preg_replace("/([\"\'])/", "\\\\\${1}", $strVal);

preg_replace()在我的Windows 7操作系统中是不稳定的,有时它会给出一个结果,有几天它会给出另一个结果吗?

请问您遇到过这种情况,为什么?

增加:

我忘记了几周之前我们已经将PHP 5.3更新为PHP5.5.3,preg_repace()根据PHP版本不稳定,而不是日期时间函数:

preg_replace("/([\"\'])/", "\\\\1", $strVal); // is OK for PHP5.3.x, but
preg_replace("/([\"\'])/", "\\\\1", $strVal); // is bad for PHP5.5.x.
preg_replace("/([\"\'])/", "\\\\\${1}", $strVal); // is good for PHP5.5.x.

就是这样,我没有多个版本的PHP,你能确认吗?

1 个答案:

答案 0 :(得分:2)

preg_*函数首先与$1一起使用效果更好,建议您使用它们。也就是说,为什么不使用addslashes来完成这项任务呢?

相关问题