php-regexHow to find all matches when using regex in PHP?
To find all matches when using regex in PHP, you can use the preg_match_all()
function. This function takes two parameters: the regular expression pattern and the string to search. It returns an array of all matches found.
Example code
$string = 'This is a string';
$pattern = '/\w+/';
preg_match_all($pattern, $string, $matches);
print_r($matches);
Output example
Array
(
[0] => Array
(
[0] => This
[1] => is
[2] => a
[3] => string
)
)
Code explanation
$string
: The string to search.$pattern
: The regular expression pattern.preg_match_all()
: The function used to find all matches.$matches
: The array of all matches found.print_r()
: The function used to print the array of matches.
Helpful links
More of Php Regex
- How to get the first match when using regex in PHP?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match a zip code?
- How to use PHP regex to match special characters?
- How to use PHP regex to match an exact string?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match URL path?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match a year?
See more codes...