用PHP实现background-image style属性的取值

w6lpcovy  于 2023-04-28  发布在  PHP
关注(0)|答案(1)|浏览(156)

我有下面的HTML代码:

<div class="article__img has-caption" style="background-image: url('img/main/article-plug.png')" >

我试图提取一个图像URL并将其替换为另一个(例如img/main/article-plug。webp),但我被XPath查询卡住了,不知道该怎么办。
提前感谢帮助!
这是我的最后一个代码(但它还没有返回任何东西):

$domDocument = new DOMDocument();
$domDocument->loadHTML($article["DESCRIPTION"]);

$domXPath = new DOMXPath($domDocument);

$img = $domXPath->query('substring-before(substring-after(//div[@class=\'article__img has-caption\']/@style, "background-image: url(\'"), "\')")');
pw9qyyiw

pw9qyyiw1#

最后,在dlporter98的帮助下,我能够解决我的问题,如果有人会面临同样的问题,这里有一个代码:

$domDocument = new DOMDocument();
$domDocument->loadHTML(mb_convert_encoding($html, "HTML-ENTITIES", "UTF-8"));

$domXPath  = new DOMXPath($domDocument);
$divs = $domXPath->evaluate("//div[@class=\"article__img has-caption\"]");
foreach ($divs as $div) {
    $style = $div->getAttribute("style");

    $url = $domXPath->evaluate("substring-before(substring-after(@style, \"background-image: url('\"), \"')\")", $div);

    $div->setAttribute("style", str_replace($url, Webp::getFromUrl($url), $style));
}

$html = mb_convert_encoding($domDocument->saveHTML(), "UTF-8", "HTML-ENTITIES");

相关问题