I have an array of patterns:
$patterns= array(
'#http://(www\.)?domain-1.com/.*#i',
'#http://(www\.)?domain-2.com/.*#i',
...
);
and I have long string that contains multiple text and urls I want to match the first url occurred in the string, I only tried this :
foreach ($patterns as $pattern) {
preg_match($pattern, $the_string, $match);
echo '<pre>'; print_r($match); echo '</pre>';
}
It returns empty arrays where there are no match for some patterns and arrays that contains a url but depending on the order of the array $patterns,
how can I find any match of these patterns that occurred first.
You basically have three options:
PREG_OFFSET_CAPTUREflag to get the offset the pattern matched at. find the lowest offset, return your resultOption 2:
beware that I changed your demo patterns. I replaced
.*(anything) by[^\s]*(everything but space) to prevent the pattern from matching more than it’s supposed to