Skip to content
Advertisement

how to remove a tag and its contents using regular expression?

$str = ‘some text tag contents more text ‘;

My questions are: How to retrieve content tag <em>contents </em> which is between <MY_TAG> .. </MY_TAG>?

And

How to remove <MY_TAG> and its contents from $str?

I am using PHP.

Thank you.

Advertisement

Answer

If MY_TAG can not be nested, try this to get the matches:

preg_match_all('/<MY_TAG>(.*?)</MY_TAG>/s', $str, $matches)

And to remove them, use preg_replace instead.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement