CancelImage Upload

How to remove image tags from a html string with preg_replace in PHP

On a dynamic website, such as a forum, users often get the feeling they can post all kinds of dodgy images to their heart's desire. Now while most webmasters would either A. Let their visitors have their fun, or B. Go nuclear, and ban their visitors from interacting with HTML code, there is another way.

Using preg_replace and some ingeniously designed regular expression code you can indeed just remove the image tags. I must warn you though, your popularity among the visitors of your website may go down;-)!

Here is how it is done:

<?php

$html = "Some <img src='dummy.jpg'/> dummy <img src='dummy.jpg'/> tex with a few dummy <img src='dummy.jpg'/> images and a <a href='http://www.link.com'>Link</a>!";

$html = preg_replace('/(<)([img])(\w+)([^>]*>)/', '', $html);

echo $html;

?>

As you can see the first two brackets look for the img openers (<img), w+ allows any kind of symbol, right up until the tag becomes closed: ([^>]*>). Happy image removing!

Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com