preg匹配所有不保存所有匹配

时间:2015-06-03 11:04:29

标签: php regex preg-match preg-match-all

以下是我必须过滤的文字示例:

12:00 NAME HTG DAW SDAWERWF 15:00 NUM LEON PARA 20: PEAX SHU MAN POP

我有这个正则表达式:/([0-9]{2})(.*)([0-9]{2})/

在此代码中:preg_match_all ($pattern,$string,$matches);

问题是:它会在$matches中保存第一场比赛,但第二场比赛没有保存。

预期产出:

array(){
 0 => 12
 1 => :00 NAME HTG DAW SDAWERWF
 2 => 15
 3 => :00 NUM LEON PARA
}

等等。

我该怎么做才能解决这个问题?

3 个答案:

答案 0 :(得分:0)

这就是你想要的:

$string = '12:00 NAME HTG DAW SDAWERWF 15:00 NUM LEON PARA 20: PEAX SHU MAN POP';

preg_match_all('/(\d\d)(.+?)(?=\d|$)/', $string, $m);
print_r($m);

<强>输出:

Array
(
    [0] => Array
        (
            [0] => 12:
            [1] => 00 NAME HTG DAW SDAWERWF 
            [2] => 15:
            [3] => 00 NUM LEON PARA 
            [4] => 20: PEAX SHU MAN POP
        )

    [1] => Array
        (
            [0] => 12
            [1] => 00
            [2] => 15
            [3] => 00
            [4] => 20
        )

    [2] => Array
        (
            [0] => :
            [1] =>  NAME HTG DAW SDAWERWF 
            [2] => :
            [3] =>  NUM LEON PARA 
            [4] => : PEAX SHU MAN POP
        )

)

答案 1 :(得分:0)

将您需要的所有内容组合在一起

$string = "12:00 NAME HTG DAW SDAWERWF 15:00 NUM LEON PARA 20: PEAX SHU MAN POP";
$pattern = '/([0-9]{1,2})(:.*[^\d])([0-9]{1,2})(:.*[^\d])[0-9]{1,2}:/';

preg_match_all ($pattern,$string,$matches);
array_shift($matches);

var_dump($matches);

输出

array(4) {
  [0]=>
  array(1) {
    [0]=>
    string(2) "12"
  }
  [1]=>
  array(1) {
    [0]=>
    string(26) ":00 NAME HTG DAW SDAWERWF "
  }
  [2]=>
  array(1) {
    [0]=>
    string(2) "15"
  }
  [3]=>
  array(1) {
    [0]=>
    string(18) ":00 NUM LEON PARA "
  }
}

working

答案 2 :(得分:0)

您可以使用此正则表达式:

'~\b(:?\d{2}.*?)(?=\h*:?\d{2})~'

RegEx Demo