【问题标题】:Replace all occurrences inside pattern替换模式内的所有匹配项
【发布时间】:2012-05-18 10:17:12
【问题描述】:

我有一个这样的字符串

{{ 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: ### }}

我想这个例子很简单,我不确定我能否更好地用文字解释我想要实现的目标。

我尝试了几种不同的方法,但都没有奏效。

【问题讨论】:

    标签: php regex preg-replace pcre


    【解决方案1】:

    这可以通过一个正则表达式回调一个简单的字符串替换来实现:

    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

    【讨论】:

      【解决方案2】:

      您可以使用 2 个正则表达式来做到这一点。第一个选择{{}} 之间的所有文本,第二个将@ 替换为###。可以像这样使用 2 个正则表达式:

      $str = preg_replace_callback('/first regex/', function($match) {
          return preg_replace('/second regex/', '###', $match[1]);
      });
      

      现在您可以制作第一个和第二个正则表达式,自己尝试一下,如果您不明白,请在这个问题中提问。

      【讨论】:

      • 在 preg_replace_callback 中的 preg_replace 会因为两次找到一个字符串而影响性能?
      【解决方案3】:

      另一种方法是使用正则表达式(\{\{[^}]+?)@([^}]+?\}\})。您需要运行几次才能匹配多个@s 内的{{ 大括号}}

      <?php
      
      $string = '{{ some text @ other text @ and some other text }} @ this should not be replaced {{ but this should: @ }}';
      $replacement = '#';
      $pattern = '/(\{\{[^}]+?)@([^}]+?\}\})/';
      
      while (preg_match($pattern, $string)) {
          $string = preg_replace($pattern, "$1$replacement$2", $string);
      }
      
      echo $string;
      

      哪些输出:

      {{ some text ### other text ### and some other text }} @ 这应该 不会被替换 {{ 但这应该是:### }}

      【讨论】:

        猜你喜欢
        • 2016-11-04
        • 1970-01-01
        • 1970-01-01
        • 2021-12-11
        • 2018-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-04
        相关资源
        最近更新 更多