phpregexpreg-matchmatchingmultiple-occurrence

How to make preg_match() match more than once?


I am trying to extract substrings matching given regex expression from the string below:

"Lorem ipsum dolor sit amet. <xy:abc_ref d_id="1234">Lorem ipsum dolor sit amet. <xy:abc_ref d_id="5678">Lorem ipsum dolor sit amet.<xy:abc_ref d_id="1234">"

Regex does match it as expected. However, for some reason I can only access the first parsed value. Even though the counter (count($matches)) states there are two results, see the output.

$value = 'Lorem ipsum dolor sit amet. <xy:abc_ref d_id="1234">Lorem ipsum dolor sit amet. <xy:abc_ref d_id="5678">Lorem ipsum dolor sit amet.<xy:abc_ref d_id="1234">';

The source:

function test($value)
{
    $RegEx = '/<xy:abc_ref ([^>]{0,})>/';       
    $n = preg_match($RegEx,$value,$matches);
    print("Results count: " . count($matches)."<br>");
    print("matches[0]: " . $matches[0]."<br>");
    print("matches[1]: " . $matches[1]."<br>");
    print("matches[2]: " . $matches[2]."<br>");
}
echo test($value);

The output:

Results count: 2
matches[0]:
matches[1]: d_id="1234"
matches[2]: 

Solution

  • Use preg_match_all to get all matches. preg_match will only return the first match. Count will return two because you capture a group.