phpregex

Regex to match HTML self closing <a/> tags (using PHP)


I had successfully used this regex to match and remove u, b, i and em self closing tags (<b/>, <i/>, ...):

$text = preg_replace('#<(u|b|i|em)(\s[^/>]*)?/>#', '', $text);

Now I also have to remove inline self closing HTML <a/> tags in a string, which content slash / characters in href attribute value (example: <a href="https://www.example.com/en-us/cinema" target="_blank" type="[object Object]"/>). So I can't just append |a in my regex list.

To avoid adding a second preg_replace line to match self closing a tags, how could I modify my existing regex? Thanks for any hints


Solution

  • This would do it :

    $text = preg_replace('#<(u|b|i|em|a)(\s[^>]*)?/>#', '', $text);