How do you only allow the first <img> tag in a string and all other <img> tags being removed using PHP function?

43 Views Asked by At

I would like to remove all HTML tags from a string with the exception of leaving the first occurrence of an tag only.

I have been playing around with the PHP strip_tags() function but have had limited success with this. I also have done an extensive amount of research to find some existing code with no success.

Does anyone have any suggestions on how this could be accomplished? I would prefer to do with with PHP and possibly the strip_tags() function.

All help is appreciated. Thanks.

1

There are 1 best solutions below

0
arkitektron On

I did figure it out with something like this for a WordPress post...

   $the_post_content = $dbh->query("SELECT post_content FROM wp_posts WHERE ID = 
   '$post_id';")->fetchColumn();    

    $the_post_content = preg_replace('/\<img/','****',$the_post_content,1);
    $the_post_content = strip_tags( $the_post_content);
    $the_post_content = str_replace('****','<img',$the_post_content);

                   $dbh->exec("UPDATE wp_posts SET post_content = 
                   '$the_post_content'
                                WHERE ID = '$post_id';");

Please note in the strip_tags() function you will need a second parameter to show which HTML tags not to remove from the string.