如何使用简单的 dom html 从后台 url 返回链接


How to return the link from background url with simple dom html?

我正在尝试获取背景的链接

<div class="mine" style="background: url('http://www.something.com/something.jpg')"></div>

我正在使用find('div.mine')

$link = find('div.mine');

$link返回包含所有

如何解析以便仅返回链接?

这种语法不太正确。你正在做$link = find('div.mine');但这应该是$link = $yourHTML->find('div.mine');的。

首先获取所有具有类名的div,mine,遍历它们,然后获取样式属性。现在你将有一个字符串,如下所示:

background: url('http://www.something.com/something.jpg') 

然后,您可以使用 CSS 解析器(推荐方式)或正则表达式从该字符串中仅获取 URL 部分。

if(preg_match('#'bhttps?://[^'s()<>]+(?:'(['w'd]+')|([^[:punct:]'s]|/))#', $link, $matches)) {
    $image_url = $matches[0];
}

完整代码:

$html = file_get_html('file.html');
$divs = $html->find('div.mine');
foreach ($divs as $div) { 
    $link = $div->style; 
}
if(preg_match('#'bhttps?://[^'s()<>]+(?:'(['w'd]+')|([^[:punct:]'s]|/))#', $link, $matches)) {
    $image_url = $matches[0];
}
echo $image_url;

输出:

http://www.something.com/something.jpg

URL匹配正则表达式模式来自Wordpress在wp-includes/formatting.php中的make_clickable函数。有关完整的实现,请参阅此帖子。

尝试使用substr()函数提取文本