htmlentities 有例外 [英] htmlentities with exceptions
本文介绍了htmlentities 有例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些可能的标签,例如 "
.我想用 htmlentities (htmlspecialchars) 处理的其余字符
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>
结果应该是
<main>
<text>
<tag> <> X&Y < <falsetag> <tag attr="123" /> </tag>
</text>
</main>
最好的方法是什么.
推荐答案
您可以在文本上运行 htmlentities 然后使用正则表达式替换允许的标签 <>
You can run htmlentities on the text then use a regular expression to replace the allowed tags <>
示例...
$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 );
这篇关于htmlentities 有例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文