tags:

views:

33

answers:

1

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() ?

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
But how can I extract the matching string then? Seems that by calling preg_match() I only know if there is match
powerboy
The third argument to `preg_match()`, if given, will be filled with the match(es).
Max Shawabkeh
@Max - exactly. That's why I linked to the manual :-)
timdev
ahh..yes..why they don't just make it a separated function? easy to ignore.
powerboy