0

I have this code that strips all HTML tags except for <img> and <p>:

<?php
        $item->core_body =strip_tags( $item->core_body, '<img><p>');
?>

Because my $item->core_body contains several <img> tags, I want to add another condition: I only want to keep the first <img> tag and strip out all the following ones.

Based on the answer:

<?php
                    $item->core_body =str_replace('<img','<***',$item->core_body,1);
                    $item->core_body =strip_tags( $item->core_body, '<img><p>');
                    $item->core_body =str_replace('<***','<img',$item->core_body,1);
?>
MagTun
  • 5,619
  • 5
  • 63
  • 104

1 Answers1

3

The simplest way: replace the first img-tag with something else, remove the rest of the image tags, replace the first tag with 'img'.

Something like

$item= preg_replace('/\<img/','****',$item,1);
$item= strip_tags( $item, '<p>');
$item= str_replace('****','<img',$item);
Michel
  • 4,076
  • 4
  • 34
  • 52
  • I have tried it but it's giving me a blank page. Any idea why? (I am editing a component on a joomla website) – MagTun Jul 23 '14 at 13:24
  • Dit you alter the variables? I did skip the `->core_body` part – Michel Jul 23 '14 at 13:28
  • Yes, i did. Sorry I didn't mention it. Please have a look at the code in my edited question. – MagTun Jul 23 '14 at 13:30
  • My bad, was an answer in a hurry. I've tested the updated answer and now it works. My error: the fourth param of `str_replace` returns the number of replacements, with `preg_replace` the fourth parameter limits the number of replacements. Furthermore, in your line `strip_tags( $item->core_body, '

    ');` the second parameter are 'allowable tags' so it would not have removed any of the `

    – Michel Jul 23 '14 at 14:49