6

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

But how can I extract the matching string then? Seems that by calling preg_match() I only know if there is match
The third argument to preg_match(), if given, will be filled with the match(es).
ahh..yes..why they don't just make it a separated function? easy to ignore.
6

Here's an example of how you can do it:

$string = 'A01B1/00asdqwe';
$pattern = '~^[A-Z][0-9][0-9][A-Z][0-9]+~';

if (preg_match($pattern, $string, $match) ) {
  echo "We have matched: $match[0]\n";
} else {
  echo "Not matched\n";
}

You can try print_r($match) to check the array structure and test your regex.

Side note on regex:

  • The tilde ~ in the regex are just delimiters needed to wrap around the pattern.
  • The caret ^ denote that we are matching from the start of the string (optional)
  • The plus + denotes that we can have one or more integers that follow. (So that A01B1, A01B12, A01B123 will also be matched.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.