1

I have a following HTML code:

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

I'm trying to extract an image URL and replace it with another (for example img/main/article-plug.webp) but I'm stuck with XPath queries and don't know what to do.

Thanks for help in advance!

That's my last code (but it doesn't return anything yet):

$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(\'"), "\')")');  
1

1 Answer 1

0

Finally, with a help from dlporter98 I was able to solve my problem, here is a code if someone will face the same problem:

$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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.