Extracting numbers from string - Why do I get two arrays when using a capture group?

60 views Asked by At

I am trying to extract numbers from a mix string.

<?php
$string = "c <a data-player-id=\"5528\" href=\"/players/5528-ga-name--5406546\" target=\"_self\">GA Name</a> b <a data-player-id=\"8992842\" href=\"/players/8992842-chandran-win--123345\" target=\"_self\">C Win</a>";

//preg_match_all('!\d+!', $string, $matches);
//preg_match_all('/data-player-id=\"(\d+)/', $string, $matches);
preg_match_all('/\/players\/(\d+)/', $string, $matches);
print_r($matches);

?>

But it results into 2 arrays:

Array
(
[0] => Array
    (
        [0] => /players/5528
        [1] => /players/8992842
    )

[1] => Array
    (
        [0] => 5528
        [1] => 8992842
    )

)

I want to capture numbers like 5528 and 8992842. The code below did not work.

 /*
 $zero = $matches[0];
 $one = $matches[1];
 $two = $matches[2];

 echo $zero;
 echo $one;
 echo $two;
 */

Edit : Any idea why it returns into 2 arrays ? Is it possible to count the items in array[1] ?

2

There are 2 answers

4
Hassaan On BEST ANSWER

You can use foreach loop print all found value in $matches[1]

Try

$string = "c <a data-player-id=\"5528\" href=\"/players/5528-ga-name--5406546\" target=\"_self\">GA Name</a> b <a data-player-id=\"8992842\" href=\"/players/8992842-chandran-win--123345\" target=\"_self\">C Win</a>";


preg_match_all('/\/players\/(\d+)/', $string, $matches);
//print_r($matches);


foreach($matches[1] as $match)
{
    echo $match."<br />";
}

output

UPDATE 1

Yes, you can count the elements found in $matches[1] by using count()

$total_matches = count($matches[1]);
echo $total_matches;
2
Pravin Vavadiya On

Try to something like this.

<?php
$string = "c <a data-player-id=\"5528\" href=\"/players/5528-ga-name--5406546\" target=\"_self\">GA Name</a> b <a data-player-id=\"8992842\" href=\"/players/8992842-chandran-win--123345\" target=\"_self\">C Win</a>";

preg_match_all('!\d+!', $string, $matches);

$arr = array_unique($matches[0]);

// For Count items...
$count = count($arr);
echo $count;

foreach($arr as $match)
{
    echo $match."<br />";
}
?>

Output

5528

5406546

8992842

123345