避免在php'中使用反向引用替换;s preg_替换
考虑以下使用避免在php'中使用反向引用替换;s preg_替换,php,regex,preg-replace,pcre,Php,Regex,Preg Replace,Pcre,考虑以下使用preg\u 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
preg\u 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
这是一个
我很清楚,实际输出并不像预期的那样,因为preg_replace
将$0、$0、$0、$1、$11和$11
视为匹配组的反向引用,将$0
替换为完全匹配,将$1和$11
替换为空字符串,因为没有捕获组1或11
如何防止preg_replace
将我的重置价值中的价格视为反向参考并试图填充它们
请注意,
$repValue
是动态的,在操作之前不会知道它的内容。在使用字符转换之前对美元字符进行转义(strtr
):
对于更复杂的情况(美元和逃逸美元),您可以进行这种替代(这次完全防水):
注意:如果
$field
仅包含文字字符串(而不是子模式),则不需要使用preg\u replace
。您可以使用str\u replace
,在这种情况下,您无需替换任何内容。否。只需特定的preg\u quote()@Deep:No,preg\u quote
仅针对模式设计,不适用于替换字符串(进行测试)。。。更换。对不起。你确定你需要使用preg\u replace
,而不是str\u replace
?@Barmar,你说得对,我实际上可以使用str\u replace
,谢谢
$repValue = strtr('$0.0 $00.00 $000.000 $1.1 $11.11 $111.111', ['$'=>'\$']);
$str = strtr($str, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']);
$repValue = strtr($repValue, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']);
$pattern = '/{{' . strtr($field, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']) . '}}/';
$str = preg_replace($pattern, $repValue, $str );
echo strtr($str, ['%%'=>'%', '$%'=>'$', '\\%'=>'\\']);