Get SRC attribute value of an image in a string

Asked

Viewed 862 times

2

I have a text where there are several registered images and the problem is this: only this tag img I know the name of id and through this id I need to know the address of the image on src.

Example:

<img id="img_blog" src="/images/blog/cliente-ideal-voce-sabe-quem-e.jpg" alt="Cliente ideal: Você sabe quem é o do seu negócio?" title="Cliente ideal: Você sabe quem é o do seu negócio?" />

I mean, I search for id="img_blog" and he returns me the address src="/images/blog/cliente-ideal-voce-sabe-quem-e.jpg".

Note: I accept Javascript solution.

1 answer

2


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...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.