How to use Regex with WP CLI to Search & Replace WordPress Database

Quick one this. WP CLI documentation on executing a search and replace on the database using regex can be confusing. Here’s a one liner that works and can eliminate some confusion. Feel free to tweak and play (on a sandbox install).

For this to run, you’ll need a WordPress install and access to WP CLI. Do not forget to replace the regex with your own.

This is the first thing you should try before trying something crude like replacing via PHP.

wp search-replace '<script.*?217bc9f0d28b2da070\.js.*?<\/script>' '' --all-tables --dry-run --report-changed-only --precise --regex --regex-delimiter='/'

Here’s a breakdown of what the above command does:

–all-tables runs the search-replace on all WordPress tables in the database.
–dry-run only shows what will be changed without actually changing anything.
–report-changed-only reports changed fields only.
–precise forces the use of PHP (instead of SQL) which is more thorough, but slower.
–regex tells WP CLI to search using the regular-expression we provided.
–regex-delimiter sets the regular-expression delimiter to ‘/’ which is the standard way of using regular-expressions in PHP.