Htmlentities with exceptions
I have several possible tags, for example "<main>", "<text>", "<tag>". The rest of the characters that I would like to handle using htmlentities (htmlspecialchars)
<main>
<text>
<tag> <> X&Y < <falsetag> <tag attr="123" /> </tag>
</text>
</main>
The result should be
<main>
<text>
<tag> <> X&Y < <falsetag> <tag attr="123" /> </tag>
</text>
</main>
What is the best way to do this.
You can run htmlentities in text and then use regex to replace valid tags <>
Example...
$str = '<main>
<text>
<tag> <> X&Y < <falsetag> <tag attr="123" /> </tag>
</text>
</main>
';
$allowed_tags = array( 'tag', 'text', 'main' );
$escaped_str = htmlentities( $str );
$replace_what = array_map( function($v){ return "~<(/?)$v(.*?)>~"; }, $allowed_tags );
$replace_with = array_map( function($v){ return "<$1$v$2>"; }, $allowed_tags );
echo preg_replace( $replace_what, $replace_with, $escaped_str );