我几乎拥有它,但它没有 100% 工作。我想从字符串中删除所有内容并仅返回图像 URL。如果字符串包含多个图像,则它将用逗号“,”分隔图像 URL。 I started with this answer到目前为止:
示例字符串(这会改变,但我需要的只是带有逗号分隔符的图像 URL,如果有多个)
<table border="0" cellpadding="8"><tr><td width="80px"><a href="https://www.ebay.com/itm/Vintage-Elegant-Clear-Glass-Light-Shade-Ceiling-3-holes-Large-Flower/183189652718?hash=item2aa6f444ee:g:ji8AAOSwzpFa20P3"><img border="0" src="https://i.ebayimg.com/thumbs/images/g/ji8AAOSwzpFa20P3/s-l225.jpg"></a></td><td><div><span><strong>$15.00</strong></span></div><div>End Date: <span>May-21 07:03</span></div><div>Buy It Now for only: US $15.00</div><a href="https://www.ebay.com/itm/Vintage-Elegant-Clear-Glass-Light-Shade-Ceiling-3-holes-Large-Flower/183189652718?hash=item2aa6f444ee:g:ji8AAOSwzpFa20P3">Buy it now</a><span> | </span><a href="http://cgi1.ebay.com/ws/eBayISAPI.dll?MfcISAPICommand=MakeTrack&item=183189652718&ssPageName=RSS:B:SHOP:US:104">Add to watch list</a></td></tr></table>
PHP:
<?php
function getImageUrlFromEbay($content = null) {
if( !empty($content)){
$imgSrc = preg_replace("/(<img\\s)[^>]*(src=\\S+)[^>]*(\\/?>)/i", "$1$2$3", $content);
return $imgSrc;
}
}
?>
如何确保该函数仅返回图像 URL?
最佳答案
使用正则表达式(假设有效的 HTML)执行此操作的粗略方法是:
if (preg_match_all('/<img .*?src=[\'"]([^\'"]+)/i', $str, $matches) > 0) {
$images = implode(',', $matches[1]);
} else {
$images = '';
}
返回 $matches[1]
数组可能比逗号分隔的字符串效果更好。理论上,URL 可以包含逗号。
不要过滤掉不属于图像 src 的 HTML,而是在 src 上进行匹配。
关于php - 删除字符串 PHP 中除图像 src URL 之外的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49990675/