删除/替换帖子内容中从X到Y的词语

时间:2018-08-31 作者:Godwin Alex Ogbonda

我正在寻找一种方法来搜索和替换数据库中的一些单词。

我在我的一个博客上有很多帖子,我想用regex替换单词。

在发布之前,我用文本标记了每个要删除/替换的位置XXXX 另一部分是YYYY

现在我有XXXX和YYYY范围内的单词。

E、 g、,

XXXX今天的新闻永远不会结束。YYYY年

现在我想删除/替换从XXXX到YYYY的所有单词

有些单词在新段落中,但在每个单词的末尾仍标有XXXX和YYYY。

我已经签出了插件和sql数据库代码,但它们都只是特定的替换词,我需要从X替换到Y

提前谢谢。

1 个回复
最合适的回答,由SO网友:David Sword 整理而成

未经测试,但我相信您可以这样做:

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
                wp_update_post(array(
                    \'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>";
            }
        }
    }
});
即使这段代码有一次试运行,always 在像这样进行大规模修改之前,请备份数据库内容并进行验证,否则很快就会出现可怕的错误。

结束