php-regexHow to get regex match in PHP?
Regex (Regular Expression) is a powerful tool used to match patterns in strings. In PHP, you can use the preg_match()
function to get a regex match.
Example code
$string = 'The quick brown fox jumps over the lazy dog.';
$pattern = '/quick (brown)(.*) jumps/';
if (preg_match($pattern, $string, $matches)) {
echo 'Match found!';
echo '<pre>';
print_r($matches);
echo '</pre>';
} else {
echo 'No match found.';
}
Output example
Match found!
Array
(
[0] => quick brown fox jumps
[1] => brown
[2] => fox
)
Code explanation
$string
: The string to search in.$pattern
: The regex pattern to match.preg_match()
: The function used to search for a match.$matches
: An array containing the matches.
Helpful links
More of Php Regex
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match a zip code?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match an exact string?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match a boolean value?
- How to use PHP regex to match a hashtag?
- How to use PHP regex to match UUID?
See more codes...