Useful Snippets


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

Are your smart devices spying on you? Make better purchasing choices and find products that respect your privacy at

RSS Latest posts from my personal blog

Most viewed posts

Subscribe to RSS feed

Cleaning up hacked WordPress spam, content injection and defacement using WP-CLI regex search

Stanislav KhromovStanislav Khromov

This post will show how you can use the build in search-replace function in WP-CLI with regex matching to batch remove harmful content from your WordPress site. This means that you can remove hundreds or thousands of injections in a matter of seconds instead of going through content and dumps manually.

Example of post_content injection:

Lorem ipsum dolor sit amet. <script src="" type="text/javascript"></script><script src="" type="text/javascript"> </script>Lorem ipsum dolor sit amet.

Go to and figure out a good regex that fits your type of defacement.

For the defacement above, I settled with:


Now it’s time to run WP-CLI to remove the defacement.

It’s always good to test first with the --dry-run flag, which simulates a run but doesn’t actually do any replacements.

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

WP-CLI will tell you how many replacements are expected. When you feel like you’ve got a good result, remove --dry-run and you get the final command to run:

wp search-replace '<script.*?tk.*?<\/script>' '' --all-tables --report-changed-only --precise --regex --regex-delimiter='/'


Using Regex with WP CLI to Search & Replace in the Database

Web Developer at Aftonbladet (Schibsted Media Group)
Any opinions on this blog are my own and do not reflect the views of my employer.
Twitter Profile
Visit my other blog

Comments 0
There are currently no comments.