Manhhailua Manhhailua - 2 years ago 131
HTML Question

Regex to remove all empty HTML tags

This is my PHP functions to remove all empty HTML tags from string input:

* Remove the nested HTML empty tags from the string.
* @param $string String to remove tags
* @param null $replaceTo Replace empty string with
* @return mixed Cleaned string
function crl_remove_empty_tags($string, $replaceTo = null)
// Return if string not given or empty
if (!is_string($string) || trim($string) == '') return $string;

// Recursive empty HTML tags
return preg_replace(
!is_string($replaceTo) ? '' : $replaceTo,

My regex:

I tested it with and, it worked well.
But when I tried to run it. Server always returned the error:

Warning: preg_replace(): Unknown modifier '\'

I have no idea what excactly '\' goes wrong. Someone please help me out!

Answer Source

In php regular expressions you need to escape your delimiters if they occur literally within your expression.

In your case, you have two unescaped /; simply replace them with \/. You also don't need the array of modifiers -- php is global by default, and you have no literal word characters defined.




//                                                                    ^       ^
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download