MagTun
MagTun

Reputation: 6185

PHP: Remove all <img> tag except for first one

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

Upvotes: 0

Views: 678

Answers (1)

Michel
Michel

Reputation: 4157

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

Upvotes: 3

Related Questions