首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >避免在php的preg_replace中进行反向引用替换

避免在php的preg_replace中进行反向引用替换
EN

Stack Overflow用户
提问于 2016-10-10 23:34:33
回答 1查看 583关注 0票数 2

考虑以下使用preg_replace的情况

代码语言:javascript
复制
$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是动态的,它的内容在操作之前不会被知道。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-10 23:43:45

在使用字符转换(strtr)之前转义美元字符:

代码语言:javascript
复制
$repValue = strtr('$0.0 $00.00 $000.000 $1.1 $11.11 $111.111', ['$'=>'\$']);

对于更复杂的案件(美元和转义美元),你可以做这种替代(这次完全防水)。

代码语言:javascript
复制
$str = strtr($str, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']);
$repValue = strtr($repValue, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']);
$pattern = '/{{' . strtr($field, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']) . '}}/';
$str = preg_replace($pattern, $repValue, $str );
echo strtr($str, ['%%'=>'%', '$%'=>'$', '\\%'=>'\\']);

注意:如果$field只包含文字字符串(而不是子模式),则不需要使用preg_replace。您可以使用str_replace代替,在这种情况下,您不需要替代任何东西。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39968330

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档