【问题标题】:PHP preg_match_all / Regular Expression IssuePHP preg_match_all / 正则表达式问题
【发布时间】:2013-02-12 00:09:28
【问题描述】:

我有一串如下所示的文本:

2012-02-19-00-00-00+136571235812571+UserABC.log

我需要把它分成三段数据:第一个 + (2012-02-19-00-00-00) 左边的字符串,两个 + (136571235812571) 和字符串+ (UserABC.log) 的右侧。

我现在有这个代码:

preg_match_all('\+(.*?)\+', $text, $match);

我遇到的问题是上面的代码返回:+136571235812571+

有没有办法使用 RegEx 为我提供所有三个数据(不带 + 标记),还是我需要不同的方法?

谢谢!

【问题讨论】:

    标签: php regex preg-match-all


    【解决方案1】:

    这基本上是用explode()完成的:

    explode('+', '2012-02-19-00-00-00+136571235812571+UserABC.log');
    // ['2012-02-19-00-00-00', '136571235812571', 'UserABC.log']
    

    您可以使用list() 将它们直接分配给变量:

    list($date, $ts, $name) = explode('+', '2012-02-19-00-00-00+136571235812571+UserABC.log');
    

    另见:explode()list()

    【讨论】:

      【解决方案2】:

      使用preg_split():

      $str = '2012-02-19-00-00-00+136571235812571+UserABC.log';
      $matches = preg_split('/\+/', $str);
      print_r($matches);
      

      输出:

      Array
      (
          [0] => 2012-02-19-00-00-00
          [1] => 136571235812571
          [2] => UserABC.log
      )
      

      使用preg_match_all()

      $str = '2012-02-19-00-00-00+136571235812571+UserABC.log';
      preg_match_all('/[^\+]+/', $str, $matches);
      print_r($matches);
      

      【讨论】:

        【解决方案3】:

        如果您想进行微优化,这可以在不使用 RegEx 的情况下“更快”完成。显然,这取决于您编写代码的上下文。

        $string = "2012-02-19-00-00-00+136571235812571+UserABC.log";
        $firstPlusPos = strpos($string, "+");
        $secondPlusPos = strpos($string, "+", $firstPlusPos + 1);
        $part1 = substr($string, 0, $firstPlusPos);
        $part2 = substr($string, $firstPlusPos + 1, $secondPlusPos - $firstPlusPos - 1);
        $part3 = substr($string, $secondPlusPos + 1);
        

        此代码需要 0.003,而我的计算机上的 RegEx 需要 0.007,但当然这会因硬件而异。

        【讨论】:

        • 不错的解决方案,但我宁愿使用简短而干净的代码(爆炸),+1 想法:)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-24
        • 2016-08-08
        相关资源
        最近更新 更多