Replace all quotes (") inside HTML tags using PHP

If you've ever stored HTML tags in a database and filtered the contents through PHP's htmlentities(), you've probably run into the problem of the quotes inside the tags being converted into " entities.

Example:

<a href="http://www.epigroove.com/">Epigroove.com</a>

turns into:

<a href="http://www.epigroove.com/">Epigroove.com</a>

Most browsers can handle this, but IE can not.

Solution:

$text = preg_replace('/<([^<>]+)>/e', '"<" .str_replace(""", \'"\', "$1").">"', $text);

This replaces all instances of '"' inside HTML tags.

elena May 11, 2012

Thanks! i always struggle with regex so it was helpful :-)

Leave a Comment