【问题标题】:Mysql Replace text contained between two patternsMysql替换两个模式之间包含的文本
【发布时间】:2014-10-24 17:40:49
【问题描述】:

我想更改 wordpress wp_posts 表上的简码。在 post_contents 字段中,我有一些带有几个短代码的 html 代码,如下所示:

[PFltr "this text is variable, changes on each occurrence"]

我想为此改变:

[scode option="1"]this text is variable changes on each occurrence[/scode]

是否有任何 mysql 更新查询,可能使用正则表达式来执行此操作?

【问题讨论】:

标签: mysql regex wordpress replace


【解决方案1】:

这段代码会做你的事:

add_action('template_redirect', 'update_my_content_shortcodes');
function update_my_content_shortcodes() {
    global $wpdb;
    $posts = $wpdb->get_results(
        "SELECT ID, post_content
         FROM $wpdb->posts
         WHERE post_content LIKE '%[PFltr%'
    "); 

    foreach ($posts as $p) {
        $updated_content = preg_replace('~\[PFltr\s*\"([^\"]*)\"\]~', '[scode option="1"]$1[/scode]', $p->post_content);
        wp_update_post(array(
            'ID' => $p->ID,
            'post_content' => $updated_content
        ));
    }
}

它会在您在前端打开 WordPress 后执行。 请注意,它会在每次页面加载时执行,因此您可能只想执行一次,或者在某些条件下执行。

【讨论】:

    【解决方案2】:

    由于这被标记为,您可以使用

    /\[PFltr\s"([^"]+)"]/ 并替换为 [scode option="1"]$1[/scode]

    DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 2012-06-16
      相关资源
      最近更新 更多