加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 替换模式中的所有实例

发布时间:2020-12-13 13:28:56 所属栏目:PHP教程 来源:网络整理
导读:我有一个像这样的字符串 {{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }} 我希望它成为 {{ some text ### other text ### and some other text }} @ this should not be replaced {{ but this
我有一个像这样的字符串
{{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }}

我希望它成为

{{ some text ### other text ### and some other text }} @ this should not be replaced {{ but this should: ### }}

我想这个例子很直接,我不确定我能更好地解释我想要用语言实现的目标.

我尝试了几种不同的方法但没有效果.

这可以通过正则表达式回调到简单的字符串替换来实现:
function replaceInsideBraces($match) {
    return str_replace('@','###',$match[0]);
}

$input = '{{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }}';
$output = preg_replace_callback('/{{.+?}}/','replaceInsideBraces',$input);
var_dump($output);

我选择了一个简单的非贪婪的正则表达式来找到你的大括号,但你可以选择改变它以提高性能或满足你的需要.

匿名函数允许您参数化替换:

$find = '@';
$replace = '###';
$output = preg_replace_callback(
    '/{{.+?}}/',function($match) use ($find,$replace) {
        return str_replace($find,$replace,$match[0]);
    },$input
);

文档:http://php.net/manual/en/function.preg-replace-callback.php

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读