php - 修复 WordPress 数据库中保存的大量 html block 中的链接 href 和 img src 不匹配的问题

标签 php mysql regex wordpress

使用缓存插件修复大量热链接后,生成的一些保存到数据库的 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 属性值都用双引号引起来。

关于php - 修复 WordPress 数据库中保存的大量 html block 中的链接 href 和 img src 不匹配的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5657698/

相关文章:

mysql - 原则 2 DQL 安全

python - 有没有一种优雅的方法来查看整个字符串是否只包含匹配项?

php - 如何不使用正则表达式否定前瞻来捕获整个组

php - 在 PHP 中收集远程代码覆盖率

php - 在 zf2 中调用存储过程时发生 PDO::MYSQL_ATTR_USE_BUFFERED_QUERY 错误

php - 在 PHP 和 MySQL 中组织和管理数千个 PDF 文件

Python mysql 函数输出不起作用

PHP curl_exec() 返回不完整的数据

mysql - 如何在多对多中只选择匹配所有参数的

javascript - 有效 java 标识符的正则表达式