1

I need remove all img element in html that non contain src attribute with preg_match and PHP

something like:

<html>
 <img src="someurl" alt="something"  />
 <img  alt="something"  />
<html />

in

<html>
 <img src="someurl" alt="something"  />
<html />

Tanks

Bolza
  • 1,904
  • 2
  • 17
  • 42
Dennais
  • 476
  • 5
  • 14

1 Answers1

2

In case your boss insists on a regex, and (s)he does not hear to the voice of wisdom, you can try the following regex:

(?si)\s*<img\b(?>(?!src=).)*?\/>\s*

See demo on regex101.

Sample PHP code:

$re = "/(?si)\\s*<img\\b(?>(?!src=).)*?\\/>\\s*/"; 
$str = "<html>\n <img src=\"someurl\" alt=\"something\"  />\n <img  alt=\"something\"  />\n <img  alt=\"somethingelse\"\n       att='val'  />\n<html />"; 
$result = preg_replace($re, "", $str);
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563