-1

I've got a string, $content, that contains:

<p>Some random text <img class="alignnone" src="logo.png" alt="" width="1920" height="648"></p>

Now I want to delete the image tag:

<img class="alignnone" src="logo.png" alt="" width="1920" height="648">

I tried strip_tags but that isn't working anymore.

$content = strip_tags($content, '<img></img>');
ElefantPhace
  • 3,806
  • 3
  • 20
  • 36
Chiel
  • 83
  • 10

3 Answers3

1

Here is a complete working example.

<?php

$content = "<p>Some random text <img class=\"alignnone\" src=\"logo.png\" alt=\"\" width=\"1920\" height=\"648\"></p>";

echo strip_tags($content,"<p>");

?>
kkaosninja
  • 1,301
  • 11
  • 21
0

If <p></p> is the only other tag you'll have you can use strip_tags like this:

$content = strip_tags($content, '<p></p>');

If there may be other tags you want to keep, just add them to the second argument of strip_tags

You can also use a combination of string functions to achieve this:

$count = substr_count($c, '<img ');
while($count >= 1){

    $i = strpos($c, '<img ');
    $j = strpos($c, '>',$i)+1;
    $c = substr($c, 0,$i) . substr($c,$j);

    $count--;
}
echo $c;

This also takes care of multiple <img> tags

ElefantPhace
  • 3,806
  • 3
  • 20
  • 36
-1

You could search for the img-Tags with the strpos()-function: http://www.w3schools.com/php/func_string_strpos.asp

Once you know the start- and ending-position inside the string you can access the parts you need with the substr()-function: http://php.net/manual/de/function.substr.php

In your example:

$left = strpos($content,'<img');
//$left should now be "20"
//to find the closing >-tag you need the string starting from <img... so you assign that to $rest:
$rest = substr($content,(strlen($content)-$left+1)*(-1));
$right = strpos($rest,">")+$left;
//now you know where the img ends so you can get the string surrounding it with:
$surr = substr($content,0,$left).substr($content,(strlen($content)-$right)*(-1));

Edit: Tested, will work for deleting the first img-Tag

codepearlex
  • 544
  • 4
  • 20