0

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.

0

1 Answer 1

3

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

5 Comments

Oh, this is a better approach. I was going the other way 3v4l.org/e2Xa1
@user3783243 That is another way of doing it indeed. Maybe the OP is also interested in that approach, you can always post it.
You may omit iterator_to_array and iterate over $elm->attributes directly.
@MarkusZeller Yes you can, but if you omit that you will not get the desired output in this case 3v4l.org/C9kFU
Correct. Thanks for the hint!

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.