Remove text from a PHP string

I have the following code being echoed:

<img src="image.png" />
Event 1

I only want the img tag to be echoed.

Read More

I’ve tried using <?php echo strip_tags($value, '<img>'); ?> but because the tag isn’t actually a proper HTML tag I don’t know how to remove it. Is there a function which will remove the text from a string?

Would str_replace work?

Related posts

Leave a Reply

5 comments

  1. usually, regular expression is not recommended for HTML parsing. But if you just want something quick, you can use:

    <?php
    
    $s = '[caption id="attachment_13" align="alignnone" width="235" caption="Event 1"]
       <img src="image.png" />
    [/caption] ';
    
    if (preg_match('/<img[^>]*>/', $s, $matches)) echo $matches[0];
    
    ?>
    

    output:

    <img src="image.png" />
    
  2. Try

    $str = "[caption id="attachment_13" align="alignnone" width="235" caption="Event 1"]
       <img src="image.png" />
    [/caption] ";
    $arr = explode ( '<img' , $str);
    $arr2 = explode ( '>' , $arr[1]);
    
    echo '<img' . $arr2[0] . '>';
    
  3. You could, however, change the [] with <> and then do the strip_tags

    $replaceThis = array('[', ']');
    $withThis = array('<', '>');
    echo strip_tags(str_replace($replaceThis, $withThis, $value), '<img>');