搜索+替换mySQL数据

时间:2011-12-10 12:44:52

标签: php mysql

我们的论坛基于phpbb3,有时候我们一直在使用语法高亮mod。我们决定放弃mod并返回基本的bbcode标签。长话短说 - 我需要更新包含以下内容的mySQL字段(phpbb_forum_posts,post_text):

Text Text Text Text Text 
[swordfish filename=code.bas]
code code code
123
code code[/swordfish]
Text Text Text Text Text 

Text Text Text Text Text 
[code]
code code code
123
code code[/code]
Text Text Text Text Text 

值得强调的是,[swordfish filename=code.bas]可以包含其他字段,例如[swordfish filename=code.bas abc 123]。无论第一个标签中的内容是什么,都需要更改为[code]

这有点超出了我的“需要知道”范围,如果有人可以帮助设计mySQL或PHP脚本来实现大规模更新,我将非常感激。 (我知道我的基本方法,不足以进行高级搜索/替换)

1 个答案:

答案 0 :(得分:0)

你走了:

$regexp = '/\[(\/)?swordfish[^\]]*\]/';

$push = 'REPLACE whatever_table (id, post_text)
          VALUES';

$pull = 'SELECT id, post_text
           FROM whatever_table
          WHERE whatever = condition';

if ( $result = $mysqli->query($pull) ) {
    while ( $row = $result->fetch_assoc() ) {
        $row['post_text'] = preg_replace($regexp, '[$1code]', $row['post_text']);

        $push .= sprintf(
            ' ("%s", "%s"),',
            $mysqli->real_escape_string($row['id']),
            $mysqli->real_escape_string($row['post_text'])
        );
    }

    $result->free();
}

$mysqli->query(rtrim($push, ','));

修改
请注意,REPLACE声明尚未完成!您必须获取每一列并将其写回(而不仅仅是我提到的两列)。