Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx in PHP: find the first matching string

Tags:

regex

php

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?

like image 382
powerboy Avatar asked Jan 23 '23 04:01

powerboy


2 Answers

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.

like image 176
timdev Avatar answered Feb 01 '23 01:02

timdev


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.
like image 25
Ernest Han Avatar answered Feb 01 '23 00:02

Ernest Han