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 with zero or more occurrences?
- How to match a space using PHP regex?
- How to match a single quote in PHP regex?
- How to use PHP regex to get a YouTube video ID?
- 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 year?
- How to use the "s" modifier in PHP regex?
- How to replace a tag using PHP regex?
See more codes...