为了转义双引号或单引号,我使用了正则表达式反向引用:
$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>"
双引号替换为错误的 ''1 字符串。
现在我必须使用它:
$strVal = preg_replace("/(['"''])/", "'''''${1}", $strVal);
preg_replace() 在我的 Windows 7 操作系统中不稳定,有时它会给出一个结果,有时它会给出另一个结果?
请问您是否遇到过这种情况,为什么?
添加:
我忘记了我们在几周前将 PHP 5.3 更新为 PHP5.5.3,根据 PHP 版本,preg_repace() 不稳定,而不是日期时间的功能:
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,你能确认吗?
preg_*
函数首先与$1
配合使用效果更好,建议您使用它们。也就是说,为什么不直接使用 addslashes
来完成此任务呢?