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

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.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.