PHP - remove <img> tag from string

PhpString

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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);

Solution 3 - Php

I would suggest using the strip_tags method.

Solution 4 - Php

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!!!

Solution 5 - Php

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; 
}

Solution 6 - Php

$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

Solution 7 - Php

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');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMikeView Question on Stackoverflow
Solution 1 - PhpSean BrightView Answer on Stackoverflow
Solution 2 - PhpJohn KugelmanView Answer on Stackoverflow
Solution 3 - PhpBen SView Answer on Stackoverflow
Solution 4 - PhpYunieskidView Answer on Stackoverflow
Solution 5 - PhpLaura MurrayView Answer on Stackoverflow
Solution 6 - Phpsolihin al mujahidinView Answer on Stackoverflow
Solution 7 - PhploroView Answer on Stackoverflow