【问题标题】:Regular Expressions (Specifically preg_split() PHP)正则表达式(特别是 preg_split() PHP)
【发布时间】:2016-08-12 20:21:38
【问题描述】:

我在我的 PHP 应用程序中列出了一些日期,结果如下:

April2016May2016June2016

我正在尝试使用preg_split 来格式化它们:

array('April 2016', 'May 2016', 'June 2016')

我使用在线正则表达式编辑器来确定如何检测 4 个连续的数字,这是我得到的结果:

注意:我还要删除所有空格 - 理想情况下,如果它只删除超过 2 个空格的空格会更好,即 hello world 不会被更改,但 hello world 会。

preg_split('/\d\d\d\d/g', preg_replace('!\s+!', '', $sidebar_contents));

使用上述内容,我收到一个错误,提示 g 标识符无效,假设因为它不是 preg_match_all - 删除 g 结果如下:

感谢您的帮助!

【问题讨论】:

标签: php regex wordpress preg-match preg-split


【解决方案1】:

这是一种实现您想要的方法,只需调用preg_match_all 并在之后使用array_map

preg_match_all('~(\p{L}+)(\d+)~', "April2016May2016June2016", $m);
$result = array_map(function($k, $v) { return $k . " " . $v; }, $m[1], $m[2]);
print_r($result);

查看regex demoIDEONE demo

图案的意思:

  • (\p{L}+) - 匹配并捕获到第 1 组(将在通过 $m[1] 匹配后访问)一个或多个字母
  • (\d+) - 匹配并捕获到第 2 组(将在通过 $m[2] 匹配后访问)一个或多个数字。

使用array_map,我们只需用空格连接第 1 组和第 2 组的值。

替代方案:在preg_replace_callback 中填写结果数组(只需通过一次!):

$result = array();
preg_replace_callback('~(\p{L}+)(\d+)~', function($m) use (&$result) {
    array_push($result, $m[1] . " " . $m[2]);
}, "April2016May2016June2016");
print_r($result);

请参阅IDEONE demo

【讨论】:

    【解决方案2】:

    你可以插入空格然后拆分:

    <?php
    $input = "April2016May2016June2016";
    var_dump(preg_split('/(?<=\d)(?!\d|$)/i',
      preg_replace('/(?<!\d)(?=\d)/', ' ', $input)));
    ?>
    

    输出:

    array(3) {
      [0]=>
      string(10) "April 2016"
      [1]=>
      string(8) "May 2016"
      [2]=>
      string(9) "June 2016"
    }
    

    【讨论】:

      【解决方案3】:

      试试这个:

      $str = "April2016May2016June2016"; 
      preg_match_all("/[a-z]+\\s\\d+/i", preg_replace("/([a-z]+)(\\d+)/i", "$1 $2", $str), $matches);
      print_r($matches[0]);
      

      输出:

      Array
      (
          [0] => April 2016
          [1] => May 2016
          [2] => June 2016
      )
      

      【讨论】:

      • 当您可以使用 1 个正则表达式操作时,为什么还要使用 2 个正则表达式操作?
      猜你喜欢
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 1970-01-01
      • 2020-08-10
      相关资源
      最近更新 更多