我正在尝试获取背景的链接
<div class="mine" style="background: url('http://www.something.com/something.jpg')"></div>
我正在使用 find('div.mine')
$link = find('div.mine');
$link 返回包含所有
如何解析使其仅返回链接?
我正在尝试获取背景的链接
<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 Parser(推荐方式)或正则表达式从该字符串中获取 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 来自 Wordpressmake_clickable
在wp-includes/formatting.php
. 有关完整的实现,请参阅这篇文章。
尝试使用substr()
函数来提取文本