Ramesh Ramesh - 5 months ago 9
PHP Question

regex to skip a tag if it is inside of another tag

I would like to remove anchor tag using php regex from the given string if it's not inside of another tag.

Input:

Hi Hello <a href="#">World</a>. This is <div class="some">testing <a href="#">content</a>. some more content</div>


Output:

Hi Hello. This is <div class="some">testing <a href="#">content</a>. some more content</div>


Thanks in advance.

Answer

Something like this :

$string = 'replace <a href="x">A</a> but not <div> <a>B</a> in tag </div> but also <a>C</a><div></div>';

echo preg_replace('/<a[^<]*?>([^<]*)<\/a>(?![^<]*<\/)/g', '', $string);

A negative lookahead ensures that the anchor tag isn't followed by </.
Thus it's not enclosed by another tag.

The content of the tag is in capture group 1, incase you want to replace by '\1' instead of by ''.

Comments