I want to find the first matching string in a very very long text. I know I can use preg_grep() and take the first element of the returned array. But it is not efficient to do it like that if I only need the first match (or I know there is exactly only one match in advance). Any suggestion?
A:
preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occurred.
timdev
2010-04-25 20:55:51
But how can I extract the matching string then? Seems that by calling preg_match() I only know if there is match
powerboy
2010-04-25 20:57:26
The third argument to `preg_match()`, if given, will be filled with the match(es).
Max Shawabkeh
2010-04-25 21:02:32
@Max - exactly. That's why I linked to the manual :-)
timdev
2010-04-25 21:04:19
ahh..yes..why they don't just make it a separated function? easy to ignore.
powerboy
2010-04-25 21:07:33