How to Fix "Warning: preg_match(): Unknown modifier 'g'" in PHP?

Fix for PHP "preg_match(): Unknown modifier 'g'" warning

If you try using the "g" (global) modifier with the PHP preg_match() function, then it will show a warning like the following:

Warning: preg_match(): Unknown modifier 'g' in ... on line ...

This is because preg_match() does not support the g modifier. You should instead use the preg_match_all() function, as it performs a global regular expression match.

For example, let's consider, you are using preg_match() with the following regular expression pattern that you wish to match globally:

$number = 12345;
$matches = [];

// Warning: preg_match(): Unknown modifier 'g' ...
preg_match('/\d/g', $number, $matches);

You could rewrite this using preg_match_all(), for example, like so:

$number = 12345;
$matches = [];

preg_match_all('/\d/', $number, $matches);

var_dump($matches); // [['1', '2', '3', '4', '5']]

The preg_match_all() function performs the match globally, similar to how you would expect when using the g flag. Therefore, the use of the g flag is not needed when you use the preg_match_all() function.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.