修复了保存在WordPress数据库中的大量HTML块中的链接href和img src不匹配的问题

问题描述

| 在使用缓存插件修复了许多热链接之后,一些保存到数据库中的生成的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不同意。 href是正确的。 有关如何解决的建议?我猜想我需要对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元素,此代码将IMG元素的SRC属性替换为A元素的HREF属性。假定所有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\"
更具体的选择器。