Hai Truong IT
Hai Truong IT

Reputation: 4187

How to remove image tag when empty src or without src

$content = '<img src=""><img alt="test" width="400px"><a href="https://placeholder.com"><img src="https://via.placeholder.com/350x150"></a>';
$content = preg_replace('!(<a\s[^>]+>)?<img([^>]+)src=""([^>]*)>(</a>)?!i' , '' , $content );
echo $content;

But only able to remove src="", can't remove without src

<img alt="test" width="400px"><a href="https://placeholder.com"><img src="https://via.placeholder.com/350x150"></a>

Upvotes: 1

Views: 441

Answers (1)

Nambi_0915
Nambi_0915

Reputation: 1091

Use the regex, <img(?![^>]*(src="[^"]+"))[^>]*> .

The negative lookahead (?![^>]*(src="[^"]+") will not capture the img tag with src="..."

Demo

Upvotes: 2

Related Questions