66

Hey, I need to delete all images from a string and I just can't find the right way to do it.

Here is what I tryed, but it doesn't work:

preg_replace("/<img[^>]+\>/i", "(image) ", $content);
echo $content;

Any ideas?

Mike
  • 6,854
  • 17
  • 53
  • 68

7 Answers7

171

Try dropping the \ in front of the >.

Edit: I just tested your regex and it works fine. This is what I used:

<?
    $content = "this is something with an <img src=\"test.png\"/> in it.";
    $content = preg_replace("/<img[^>]+\>/i", "(image) ", $content); 
    echo $content;
?>

The result is:

this is something with an (image)  in it.
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
  • 3
    Can you make this except of (image) it will replace with the alt of an image? – MysteryDev Aug 07 '13 at 23:04
  • Try dropping the \ in front of the >. `preg_replace("/]+\>/i", "(image) ", $content);` Hows that's different from the actual question? – fat_mike May 21 '18 at 23:05
23

You need to assign the result back to $content as preg_replace does not modify the original string.

$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
11

I would suggest using the strip_tags method.

Ben S
  • 68,394
  • 30
  • 171
  • 212
8

Sean it works fine i've just used this code

$content = preg_replace("/<img[^>]+\>/i", " ", $content); 
echo $content;

//the result it's only the plain text. It works!!!

Yunieskid
  • 81
  • 1
  • 1
1

I wanted to display the first 300 words of a news story as a preview which unfortunately meant that if a story had an image within the first 300 words then it was displayed in the list of previews which really messed with my layout. I used the above code to hide all of the images from the string taken from my database and it works wonderfully!

$news = $row_latest_news ['content'];
$news = preg_replace("/<img[^>]+\>/i", "", $news); 
if (strlen($news) > 300){
echo substr($news, 0, strpos($news,' ',300)).'...';
} 
else { 
echo $news; 
}
  • Comments use mini-Markdown formatting: [link](http://example.com) _italic_ **bold** `code`. The post author will always be notified of your comment. To also notify a previous commenter, mention their user name: – xavip Feb 17 '16 at 16:02
-2
$this->load->helper('security');
$h=mysql_real_escape_string(strip_image_tags($comment));

If user inputs

<img src="#">

In the database table just insert character this #

Works for me

Sal00m
  • 2,938
  • 3
  • 22
  • 33
-4

simply use the form_validation class of codeigniter:

strip_image_tags($str).

$this->load->library('form_validation');
$this->form_validation->set_rules('nombre_campo', 'label', 'strip_image_tags');
Stuart Siegler
  • 1,686
  • 4
  • 30
  • 38
loro
  • 1