PHP: strip_tags - remove only certain tags (and their contents)?

前端 未结 2 846
礼貌的吻别
礼貌的吻别 2020-12-11 03:21

I use the strip_tags() function but I need to remove some tags (and all of their contents).

for example :

2条回答
  •  没有蜡笔的小新
    2020-12-11 03:53

    Use a regular expression. Something like this should work:

    $tags = array( 'p', 'span');
    $text = preg_replace( '#<(' . implode( '|', $tags) . ')>.*?<\/$1>#s', '', $text);
    

    The demo shows it replacing the desired tags with nothing.

    Note that you may need to tweak it more, say, to compensate for whitespace within the tags, or other unknowns that your example does not demonstrate.

    Here is the regex to use to capture tags with or without attributes:

    '#<(' . implode( '|', $tags) . ')(?:[^>]+)?>.*?<\/$1>#s'
    

提交回复
热议问题