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 use PHP regex to get a YouTube video ID?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match special characters?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match a word?
- How to use backslash in PHP regex?
- How to use PHP regex to match UUID?
- How to use PHP regex to match UTF8?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match an XML tag?
See more codes...