Remove all Attribute from img except src and alt

61 Views Asked by At

I have a html string that contains many images.each image has some attribute like class ,id , style , ....

I want remove all attribute from img except src and alt.

before :

<img title="How to" alt="How to" src="windows_en.jpg" loading="lazy" width="1280" height="720" class="img-first">

I want this output:

<img alt="How to" src="windows_en.jpg">

I want Remove all Attribute from img except src and alt. I try this :

$desc = preg_replace("/(<img\\s)[^>]*((src|alt)=\\S+)[^>]*/i", "$1$2$3", $desc);

but not work fine. please help.

1

There are 1 best solutions below

5
The fourth bird On BEST ANSWER

You could use DOMDocument instead of a regex, and then filter out the attributes that are not "src" or "alt" using removeAttribute:

$data = <<<DATA
<img title="How to" alt="How to" src="windows_en.jpg" loading="lazy" width="1280" height="720" class="img-first">
DATA;

$dom = new DOMDocument();
$dom->loadHTML($data, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach($dom->getElementsByTagName("img") as $elm) {
  foreach(iterator_to_array($elm->attributes) as $att) {
      if ($att->name !== "src" && $att->name !== "alt") {
          $elm->removeAttribute($att->name);
      }
  }
}

echo $dom->saveHTML();

Output

<img alt="How to" src="windows_en.jpg">