我有一个基于MySQL的CMS表,其中一个字段包含了在CMS网页上显示的文章文本。
一些文章包含嵌入在文本中的图像,以HTML 'img‘标记的形式。字段中包含的文本中可能有一个或多个图像。
我想要做的是创建一个查询,该查询将提取所有文章中所有图像的列表。我已经设法创建了一些代码,如下所示:
SELECT nid,
substr(body,locate('<img', body),(locate('>',body,locate('<img', body)) - locate('<img', body))) as image,
body FROM `node_revisions` where body like '%<img%'这似乎工作得很好,当然它只提取第一个图像,我真的想提取所有的图像(事实上,这通常意味着使用循环,但这在MySQL中似乎不可能)。
仅供参考,所讨论的CMS是Drupal6,因此字段和表的名称。然而,这实际上是一个关于MySQL而不是Drupal的问题,这就是为什么我在这里而不是在Drupal Stackexchange站点上问这个问题。
发布于 2016-08-06 03:18:57
尝试使用locate()、substring()或正则表达式来解析HTML或XML会让您发疯。请参阅https://blog.codinghorror.com/parsing-html-the-cthulhu-way/
我建议你使用PHP的DOMDocument类:
<?php
$bodyHtml = "now is the time for all <img src='good.jpg'> men to come to the <img src='aid.jpg'> of their country";
$dom = new DOMDocument();
$dom->loadHTML($bodyHtml);
$imgs = $dom->getElementsByTagName("img");
foreach ($imgs as $img) {
print "$img->nodeName\n";
foreach ($img->attributes as $attr) {
print " $attr->name=$attr->value\n";
}
}输出:
img
src=good.jpg
img
src=aid.jpg发布于 2016-08-06 04:09:25
用正则表达式解析html永远不会是100%,你永远不会有信心得到每一张图片并正确格式化,
您遇到的另一个问题是您在问题中暗示的问题。node_revisions中有一条记录可能包含1张、2张或10,000张图像。在SQL中,您无法在查询结果中将每个图像作为新行返回,因此必须将每个图像作为新列返回。
这意味着您实际上需要手动指定每一列:
SELECT code_to_return_img_1 as url1
,code_to_return_img_2 as url2
,code_to_return_img_3 as url3
,code_to_return_img_4 as url4
,code_to_return_img_5 as url5
,code_to_return_img_6 as url6
....
and so on如果你知道每篇文章只有不到20张图片,而且你没有php/java/python可用,这只是你需要的一次性工作,那么你可以用regex和SQL来做,但你30分钟的工作可能会变成2天的工作和突发的静脉。
如果Java是一个选项:https://jsoup.org/
如果Python是一个选项:https://docs.python.org/2/library/htmlparser.html
如果可以选择PHP:http://htmlparsing.com/php.html
$dom = new DOMDocument;
$dom->loadHTML($html);
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
$imgurl = $image->getAttribute('src');
}https://stackoverflow.com/questions/38795759
复制相似问题