【发布时间】:2016-10-10 23:34:33
【问题描述】:
考虑下面使用preg_replace
$str='{{description}}';
$repValue='$0.0 $00.00 $000.000 $1.1 $11.11 $111.111';
$field = 'description';
$pattern = '/{{'.$field.'}}/';
$str =preg_replace($pattern, $repValue, $str );
echo $str;
// Expected output: $0.0 $00.00 $000.000 $1.1 $11.11 $111.11
// Actual output: {{description}}.0 {{description}}.00 {{description}}0.000 .1 .11 1.111
这是phpFiddle showing the issue
我很清楚,实际输出与预期不符,因为 preg_replace 正在查看 $0, $0, $0, $1, $11, and $11 作为匹配组的反向引用,将 $0 替换为完整匹配,将 $1 and $11 替换为空字符串,因为没有捕获组 1 或 11。
如何防止preg_replace 将我的重置价值中的价格视为反向引用并尝试填充它们?
注意$repValue是动态的,操作前不知道其内容。
【问题讨论】:
-
您确定需要使用
preg_replace,而不是str_replace? -
@Barmar,你说得对,我其实可以用
str_replace,谢谢
标签: php regex preg-replace pcre