【问题标题】:How do I parse a string for a particular delimited section within PHP?如何解析 PHP 中特定分隔部分的字符串?
【发布时间】:2011-01-20 20:44:52
【问题描述】:

我有一个字符串,例如“[{XYZ123}] 这是一个测试”,需要解析出 [{ 和 }] 之间的内容并转储到另一个字符串中。我认为正则表达式是为了完成此操作,但由于它不适合胆小的人,因此我没有尝试并且需要您的帮助。

将片段拉到 [{ 和 }] 之间的最佳方法是什么?提前感谢您的帮助!

【问题讨论】:

    标签: php regex parsing


    【解决方案1】:
    $str = "[{XYZ123}] This is a test";
    $s = explode("}]",$str);
    foreach ($s as $k){
      if ( strpos($k,"[{") !==FALSE ){
        $t = explode("[{",$k); #or use a combi of strpos and substr()
        print $t[1];
      }
    }
    

    【讨论】:

      【解决方案2】:
      <?php
      $str = "[{XYZ123}] This is a test";
      
      if(preg_match('/\[{(.*?)}\]/',$str,$matches)) {
      
       $dump = $matches[1];
      
       print "$dump";  // prints XYZ123
      }
      
      ?>
      

      【讨论】:

        【解决方案3】:

        正则表达式是(?=\[\{).*(?=\}\]),虽然我不知道php是否支持前瞻。

        【讨论】:

        • 如果php不支持前瞻,你可以不前瞻\[\{(.*?)\]\}
        • 没错,我只是对 php 了解不够,无法告诉他如何提取反向引用。
        • 我也不擅长 php,但如果我没记错的话,$1 语法在 php 中有效。
        猜你喜欢
        • 2011-08-04
        • 1970-01-01
        • 1970-01-01
        • 2014-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多