Reputation: 1747
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]:
Upvotes: 0
Views: 107
Reputation: 3840
function test($value)
{
$RegEx = '/<xy:abc_ref ([^>]{0,})>/';
$n = preg_match_all($RegEx,$value,$matches);
print("Results count: " . count($matches[1])."<br>");
print("matches[0]: " . $matches[1][0]."<br>");
print("matches[1]: " . $matches[1][1]."<br>");
print("matches[2]: " . $matches[1][2]."<br>");
}
Upvotes: 0
Reputation: 58962
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.
Upvotes: 2