使用缓存插件修复大量热链接后,一些生成的html保存到数据库中不太正确。例如:
<a href="http://www.mbird.com/wp-content/uploads/2011/04/psycho_blanket.jpg"><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer; width: 164px; height: 251px;" src="http://www.mbird.com/wp-content/uploads/2011/04/psycho_blanket1.jpg" alt="" id="BLOGGER_PHOTO_ID_5306768463834252178" border="0"></a>
其他时候,在扩展名之前有一个额外的2。其他时候是21.
可以看到,href和src不一致。
如何修复的建议?我猜我需要对post_content中的链接图像做一个正则表达式来测试这个?我在php中没有太多使用正则表达式的经验,需要一些帮助。
$posts = get_posts();
foreach( $posts as $post ) {
// retrieve content of post; same as $post->post_content
$content = $post['post_content'];
// do stuff that I'm unsure about with $content to hone in on linked images with mismatched filenames and fix them
// write it back
$post['post_content'] = '$content;
// Update the post into the database
wp_update_post( $my_post );
}
经过测试的正则表达式解决方案应该这样做:
$re = '% # Match IMG wrapped in A element.
(<a'b[^>]+?href=")([^"]*)("[^>]*><img'b[^>]+?src=")([^"]*)("[^>]*></a>)
%ix';
$content = preg_replace($re, '$1$2$3$2$5', $content);
给定一个包裹在A元素中的IMG元素,这段代码用A元素的HREF属性替换IMG元素的SRC属性。它假定所有的HREF和SRC属性值都用双引号括起来。
这很容易用正则表达式实现。但是我会偷懒,在这里求助于phpQuery或QueryPath(它似乎是一次性操作,所以你不需要注意性能):
$html = qp($content);
foreach ($html->find("a img") as $img) {
$img->attr("src",
$img->parent()->attr("href")
); // or maybe add some if checks here
}
$post["post_content"] = $html->top("body")->writeHTML();
不测试。您可能还需要一个比"a img"
更具体的选择器。