I am looking for a way to search and replace some words in my database.

I have many posts on one of my blog and i want to replace words using regexes.

before publishing, I marked every place I wish to delete/replace with a text XXXX and another part with YYYY

Now I have words within XXXX and YYYY.


XXXX todays news will never end. YYYY

now I want to delete/replace all the words from XXXX to YYYY

Some of the words are in new paragraph, but are still marked with XXXX and YYYY at the end of every word.

I have checked out plugins and sql database code, but all of them are just specific word replacer, I need to replace from X to Y

thanks in advance.


Untested, but I believe you can do something like this:

add_action( 'init', function() {

    // since were editing content, we want to be very very careful
    // well do a dry run output first to make sure were doing what we want
    $dryrun = true;

    // Regex pattern finds anything between the X and Y bounds.
    $pattern = '/(XXXX)(.+?)(YYYY)/gms';

    // Get and cycle through ALL published `posts`
    $all_posts = get_posts('posts_per_page=-1');
    foreach ($all_posts as $a_post) {

        // replace the pattern with our new content.
        // If the content is to be preserved, we could use $2 in the second arg
        $new_content = preg_replace($pattern, "New content here", $a_post->post_content);

        // if somthing was replaced, lets continue
        if ( $new_content != $a_post->post_content ) {

            // display what _would_ be changing
            if ( $dryrun ) {
                echo "<div>update post #{$a_post->ID} to:</div>";
                echo "<pre>{$new_content}</pre>";
            } else {
                // update the post_content with our new content
                    'ID' => $a_post->ID,
                    'post_content' => $new_content,
        } else {
            // nothing was changed, if dry run, just print the notice.
            if ( $dryrun ) {
                echo "<div>nothing to update in post #{$a_post->ID}</div>";

Even though this code has a dry run on it, always back up your database content and verify it before doing mass-modifying like this, things can go horribly wrong very quickly.

  • 2
    You could avoid risk by running the same preg_replace on 'the_content', leaving the database unaltered. – CK MacLeod Sep 1 '18 at 0:58
  • +1, yes good tip! – David Sword Sep 1 '18 at 21:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.