很有趣的问题。但恐怕这不能在 MySQL 中使用 REPLACE 或 REGEXP 语法来完成。所以我写了一个小的 wordpress 插件,用于在帖子上进行正则表达式搜索和替换。在使用插件之前,请确保备份wp_posts
表。
CREATE TABLE wp_posts_temp LIKE wp_posts;
INSERT INTO wp_posts_temp SELECT * FROM wp_posts;
插件代码
将此代码放入 wp-content/plugins/replace-in-posts/ 文件夹中的 replace.php 等文件中,然后激活插件。
<?php
/*
Plugin Name: Replace in posts
Author: Danijel
*/
add_action('admin_menu', 'replace_in_posts_menu');
function replace_in_posts_menu() {
add_options_page("Replace in posts", "Replace in posts", 'manage_options', "replace_in_posts", "replace_in_posts_admin");
}
function replace_in_posts_admin() {
if ( !empty($_POST['pattern']) && isset($_POST['replacement']) ) {
$pattern = stripslashes_deep( $_POST['pattern'] );
$replacement = stripslashes_deep( $_POST['replacement'] );
$count = replace_in_posts( '/'.$pattern.'/', $replacement );
}
?><div id="icon-options-general" class="icon32"></div><h2><?php echo 'Replace in posts' ?></h2>
<div class="wrap"><form method="post" action="<?php echo admin_url()."admin.php?page=".$_GET["page"] ?>">
Pattern (without delimiter) : <input type="text" name="pattern" value="">
Replacement: <input type="text" name="replacement" value="">
<input class="button-primary" type="submit" value="Replace" >
</form><?php if (isset($pattern)) : ?><p>Pattern "<?php echo $pattern; ?>" replaced in <?php echo ( $count ? $count : '0' ); ?> posts</p><?php endif; ?></div><?php
}
function replace_in_posts( $pattern, $replacement ) {
$myposts = get_posts('numberposts=-1');
$count = 0;
foreach ( $myposts as $post ) {
if ( preg_match( $pattern, $post->post_content ) ) {
$post->post_content = preg_replace( $pattern, $replacement, $post->post_content );
wp_update_post( $post );
$count++;
}
}
return $count;
}
?>
正则表达式模式和替换您的问题:
\[sc:youtube id="(\w+?)"\]
<iframe width="775" height="436" src="http://www.youtube.com/embed/$1?rel=0" frameborder="0" allowfullscreen></iframe>
插件已在该模式上进行了测试,并且没有错误。