RegEx in PHP: find the first matching string
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?
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.
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.
精彩评论