Search code examples
phphtmlregexsanitizationstrip-tags

Remove non-<img> tags from string


I'm trying to make this:

<span class="introduction">
   <img alt="image" src="/picture.jpg" />
</span>

transform into this:

<img alt="image" src="/picture.jpg" />

How would I do this with regex? That is, how do I extract ONLY the img-tag from a given string of html?

Note: There can be a lot more html within the introduction-tag BUT only one img-tag


Solution

  • You shouldn't really use regex on HTML, what about this:?

    $string = '<span class="introduction"><img alt="image" src="/picture.jpg" /></span>';
    
    echo strip_tags($string, '<img>');
    

    Otherwise I would use an HTML/XML parser