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

4
  • 3
    don't use regex. use dom+xpath... Commented May 6, 2015 at 16:49
  • Use a PHP DOM parser Commented May 6, 2015 at 16:51
  • In this project I can't use DOM Parser Commented May 6, 2015 at 16:55
  • See "You can't parse [X]HTML with regex ...". Commented May 6, 2015 at 17:05

1 Answer 1

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

Comments

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.