php-regexHow to get the first match when using regex in PHP?
The preg_match() function in PHP can be used to get the first match when using regex.
$string = 'The quick brown fox jumps over the lazy dog.';
$pattern = '/quick (\w+)/';
preg_match($pattern, $string, $matches);
echo $matches[0];
The output of the above code will be:
quick brown
Code explanation
$string: This is the string in which the regex pattern will be searched.$pattern: This is the regex pattern which will be used to search the string.preg_match(): This is the function which will be used to search the string for the regex pattern. It takes three parameters: the regex pattern, the string to search, and an array to store the matches.$matches: This is the array which will store the matches.echo $matches[0]: This will output the first match.
Helpful links
More of Php Regex
- How to match a single quote in PHP regex?
- How to match a double quote in PHP regex?
- How to match a quotation mark in PHP regex?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match an exact string?
- How to use quantifiers in PHP regex?
- How to use PHP regex to match a boolean value?
- How to use the "s" modifier in PHP regex?
- How to use PHP regex to match letters, numbers and underscores?
- How to use PHP regex to match a line break?
See more codes...