Search code examples
phpregexstrip-tags

Remove all tags from string except a certain regex


I've written this regex :

<span class="icon(.*?)><\/span>

And I've got this string :

<p style="text-align: center;"><span style="font-size: 1em;">Text 1 <span style="font-weight: bold;">TEXT 2</span><span style="color: #e67e23; font-size: 1.2em;"><span class="icon x-small icon-play"></span>&nbsp;</span><span style="color: #e03e2d;">Text 3</span> <span style="color: #a68965;">Text 4 </span></span><span style="font-size: 0.7em; color: #000000;">Text 5</span></p>

And I would like to remove all tags from that string except the tag resulting from the regex above. So I would get this final result :

Text 1 Text 2<span class="icon x-small icon-play"></span>&nbsp;Text 3 Text 4 Text 5

As you can see in this output, all tags have been cleared except the tag I'm looking for.

I took a look at PHP's strip_tags but unfortunately they do not take a regex as a second parameter, thus not doing what I'm looking for. I tried doing it with a preg_replace but I was not able to create such a complex regex.

Any idea on what's the best way of doing this either it is with regex or not?


Solution

  • Use

    preg_replace('/<span class="icon.*?><\/span>(*SKIP)(*F)|<[^<>]+>/', '', $string)
    

    See proof

    The expression will find <span class="icon....></span> strings to ignore them with (*SKIP)(*F) and then all other tags will be removed (matched with <[^<>]+>).