php - 删除字符串 PHP 中除图像 src URL 之外的所有内容

标签 php html

我几乎拥有它,但它没有 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;
    }
}
?>

这是我当前函数返回的预览: enter image description here

如何确保该函数仅返回图像 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/

相关文章:

php - 如何安装zend framework 2.4.11骨架应用

javascript - 如何使用 Jquery 在 HTML 表格中添加行?

javascript - 鼠标悬停时灰度

javascript - 文本的实时预览使链接在悬停时不会改变背景颜色

javascript - Backbone .js : Not rendering some view

php - 在运行时从数据库更改 Laravel 的配置

php - 我想要一个 AJAX 文件 uploader ,比如 Gmail 文件上传,在 PHP 中带有进度条

jquery - 在固定 div 内加载表单

php - 只显示一次数据

php - 如何从电子邮件地址获取 Linkedin 的头像