Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htmlentities with exceptions

I have some set of possible tags for example "<main>", "<text>", "<tag>". Rest of characters I would like to treat with htmlentities (htmlspecialchars)

<main>
<text>
<tag> <>  X&Y <  <falsetag> <tag attr="123" /> </tag>
</text>
</main>

The result should be

<main>
<text>
<tag> &lt;&gt;  X&amp;Y &lt;  &lt;falsetag&gt; <tag attr="123" /> </tag>
</text>
</main>

What's the best way to do it.

like image 276
liysd Avatar asked May 24 '26 12:05

liysd


1 Answers

You can run htmlentities on the text then use a regular expression to replace the allowed 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 "~&lt;(/?)$v(.*?)&gt;~"; }, $allowed_tags );
$replace_with = array_map( function($v){ return "<$1$v$2>"; }, $allowed_tags );

echo preg_replace( $replace_what, $replace_with, $escaped_str );
like image 60
Galen Avatar answered May 26 '26 02:05

Galen