PHP - remove the <img> tag from a string

Hey, I need to remove all the images from the row, and I just can't find the right way to do this.

Here is what I tried, but it does not work:

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

Any ideas?

+47
string php
Jul 10 '09 at 0:54
source share
8 answers

Try dropping \ before > .

Edit: I just checked 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; ?> 

Result:

 this is something with an (image) in it.
+123
Jul 10 '09 at 0:56
source share

You need to return the result of $content , since preg_replace does not change the original string.

 $content = preg_replace("/<img[^>]+\>/i", "(image) ", $content); 
+17
Jul 10 '09 at 1:01
source share

I would suggest using the strip_tags method.

+12
Jul 10 '09 at 0:57
source share

Sean works fine, I just used this code

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

// the result is only plain text. He works!!!

+7
Sep 12 2018-10-12T00:
source share

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

 $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; } 
+1
Apr 26 '13 at 15:20
source share
 $this->load->helper('security'); $h=mysql_real_escape_string(strip_image_tags($comment)); 

If user inputs

 <img src = "#">

In the database table, just insert the this # character

Works for me

-one
Jun 25 '14 at 7:56
source share
 $content = strip_tags($content, '<img>'); 

is a cleaner and easier way.

-2
May 30 '14 at 18:26
source share

just use the form_validation codeigniter class:

 strip_image_tags($str). $this->load->library('form_validation'); $this->form_validation->set_rules('nombre_campo', 'label', 'strip_image_tags'); 
-3
May 1 '15 at
source share



All Articles