考虑以下使用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
在我看来,实际输出并不像预期的那样,因为preg_replace将$0, $0, $0, $1, $11, and $11视为匹配组的后引用,用完全匹配替换$0,用空字符串替换$1 and $11,因为没有捕获组1或11。
如何防止preg_replace将我的重置价值中的价格视为反向引用并试图填充它们?
注意,$repValue是动态的,它的内容在操作之前不会被知道。
发布于 2016-10-10 23:43:45
在使用字符转换(strtr)之前转义美元字符:
$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, ['%%'=>'%', '$%'=>'$', '\\%'=>'\\']);注意:如果$field只包含文字字符串(而不是子模式),则不需要使用preg_replace。您可以使用str_replace代替,在这种情况下,您不需要替代任何东西。
https://stackoverflow.com/questions/39968330
复制相似问题