JordyvD
JordyvD

Reputation: 1615

preg match all not saving all matches

Here's an example of the text I have to filter:

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

and I have this regex: /([0-9]{2})(.*)([0-9]{2})/

in this code: preg_match_all ($pattern,$string,$matches);

Problem is: it saves the first match in $matches but the second match isn't saved.

expected output:

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

and so on.

What can I do to solve this?

Upvotes: 1

Views: 91

Answers (3)

anubhava
anubhava

Reputation: 785601

You can use this regex:

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

RegEx Demo

Upvotes: 0

splash58
splash58

Reputation: 26153

combine together all you need

$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);

output

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

Upvotes: 0

Toto
Toto

Reputation: 91488

Is that what you want:

$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);

Output:

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
        )

)

Upvotes: 0

Related Questions