How can I replace all regex matches using the WP_CLI search-replace tool

With WP CLI I can use the search-replace method like this:

wp search-replace 'foo' 'bar'

However, when I use regex, it only replaces the first occurrence within each DB field:

wp search-replace 'myRegex' 'bar' --regex

In the above example, only the first regex match for myRegex is replaced in any given DB field. I can repeatedly run the search over and over until all matches have been replaced, but I’d like to be able to do it in one command. The /g global flag is not available because when I try it:

wp search-replace 'myRegex/g' 'bar' --regex

I get a bunch of warnings that I cannot use it with php preg_replace:

PHP Warning: preg_replace(): Unknown modifier ‘g’

1 Answer
1

Under the hood, WP-CLI uses preg_replace() to perform the regex search-replace operation. By default, preg_replace() is a global operation. If WP-CLI is only replacing the first instance, there may be some other issue at hand.

If you’ve found a bug though, and can provide a test case to reproduce it, please open an issue and we can get it fixed.

Leave a Comment