【问题标题】:Regex extract string between 2 curly braces2个花括号之间的正则表达式提取字符串
【发布时间】:2013-12-14 10:47:25
【问题描述】:

我有以下短代码:

亲爱的{{name}}

您被邀请参加以下活动:{{event}}

问候,{{author}}

我有一个来自数据库的数组: $data

地点:

$data['name'] = 'John Doe';
$data['event'] = 'Party yay!';
$data['author'] = 'Kehke Lunga';

我期望的输出:

亲爱的 John Doe,

您被邀请参加以下活动:派对耶!

问候,Kehke Lunga

另外,我还想执行{{firstname||lastname}} 之类的操作,它应该检查是否设置了键$data['firstname'],如果没有设置,则应该使用$data['lastname']。不过,那是为了后期。

现在,我只想知道如何匹配两个花括号之间的文本。

谢谢

【问题讨论】:

    标签: php regex


    【解决方案1】:

    preg_match_all():

    $pattern = '~\{\{(.*?)\}\}~';
    preg_match_all($pattern, $string, $matches);
    var_dump($matches[1]);
    

    【讨论】:

      【解决方案2】:

      对于您需要的第二个操作,它可能是这样的:

      $str = "Dear {{name||email}}, You are being invited for the following event: {{event}}. Regards, {{author}}";
      
      // $data['name'] = 'John Doe'; 
      $data['email'] = 'JohnDoe@unknown.com'; 
      $data['event'] = 'Party yay!'; 
      $data['author'] = 'Kehke Lunga';
      
      $pattern = '/{{(.*?)[\|\|.*?]?}}/';
      
      $replace = preg_replace_callback($pattern, function($match) use ($data)
      {
          $match = explode('||',$match[1]);
      
          return isset($data[$match[0]]) ? $data[$match[0]] : $data[$match[1]] ;
      }, $str);
      
      echo $replace;
      

      基本上通过编辑'$pattern',然后在回调中找到所需的正确逻辑。

      【讨论】:

        【解决方案3】:

        使用preg_replace_callback:

        $data = array(
            'name' => 'John Doe',
            'event' => 'Party yay!',
            'author' => 'Kehke Lunga',
        );
        
        $str = 'Dear {{name}},
        You are being invited for the following event: {{event}}
        regards, {{author}}';
        
        $str = preg_replace_callback('/{{(\w+)}}/', function($match) use($data) {
            return $data[$match[1]];
        }, $str );
        
        echo($str);
        

        输出:

        Dear John Doe,
            You are being invited for the following event: Party yay!
            regards, Kehke Lunga
        

        【讨论】:

        • 看起来这更符合 OP 的需求。我不得不承认我刚刚阅读了问题的标题:) ...
        • 是的,这正是我所需要的
        【解决方案4】:

        使用preg_match 匹配两个大括号之间的文本:

        $subject = "{{Lorem}}";
        $pattern = '/\{\{([^}]+)\}\}/';
        preg_match($pattern, $subject, $matches);
        var_dump($matches);
        

        看看类似的Question

        【讨论】:

          【解决方案5】:
          $matches = array();
          $a="{{name}}";
          preg_match('/\{(.+)\{(.+)\}\}/', $a, $matches);
          
          var_dump($matches);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-09-29
            • 2015-07-05
            • 2021-11-24
            • 1970-01-01
            • 2011-07-17
            • 1970-01-01
            相关资源
            最近更新 更多