Javascript
With Javascript, you can create a new element programmatically, insert the contents of your string as content of this element and after using the function querySelector
to fetch the desired image and retrieve the attribute value src
. Note that the created element will exist only virtually, because it is not inserted in the body of the document.
const data = `
<img src="/images/blog/outra-imagem-A.jpg" />
<img src="/images/blog/outra-imagem-B.jpg" />
<img id="img_blog" src="/images/blog/cliente-ideal-voce-sabe-quem-e.jpg" />
<img src="/images/blog/outra-imagem-C.jpg" />
<img src="/images/blog/outra-imagem-D.jpg" />
`;
const virtual = document.createElement("div");
virtual.innerHTML = data;
const img = virtual.querySelector("#img_blog");
console.log(img.getAttribute("src"));
PHP
Already, with PHP, you can use the native class DOMDocument
to analyze the content of your string and extract the desired information:
<?php
$data = <<<HTML
<img src="/images/blog/outra-imagem-A.jpg" />
<img src="/images/blog/outra-imagem-B.jpg" />
<img id="img_blog" src="/images/blog/cliente-ideal-voce-sabe-quem-e.jpg" />
<img src="/images/blog/outra-imagem-C.jpg" />
<img src="/images/blog/outra-imagem-D.jpg" />
HTML;
$dom = new DOMDocument();
$dom->loadHTML($data);
$img = $dom->getElementById("img_blog");
echo $img->getAttribute("src"), PHP_EOL;
See working on Repl.it
Dear Anderson, I thank you for your attention for the script posted by the necessary modifications that I had to realize fit right into my needs. Hugs and a good weekend...
– Rogarfil