如何正确或安全地输出数据,但仍然能够显示中断和输入的特殊字符


How to properly or securely output data but still be able to display breaks and special characters inputed

下面的函数是我用来输出数据的函数

function escape($string){
    return htmlentities($string, ENT_QUOTES, 'UTF-8');
}

如果只需要将字符串保存到我的数据库中并得到的响应,它就可以工作

我如何允许某些标签,如粗体和breaks,仍然可以免受xss攻击

这是一个样本字符串,我需要工作

$string = '<b onclick="javascript:alert(1);">Hello<br>World<script>alert(2);</script></b>';

输出应该只是

你好
世界

我结合在这个网站上找到的答案,想出了一个解决问题的办法。

这是代码

$string = '<b onclick="javascript:alert(1);">Hello<br>World<script>alert(2);</script></b>';
// remove script tag along with everything in it
$string = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $string); 
// remove all tags except the ones you want to work
$string = strip_tags($string, '<br><b>');
// remove all attributes of the html tags
$string = preg_replace("/<([a-z][a-z0-9]*)[^>]*?('/?)>/i",'<$1$2>', $string);
echo $string;

目前,它对所提供的示例字符串有效。如果你们知道使用此代码可能出现的任何问题,请随时就安全输出数据的更好方式发表评论和建议,但仍保留某些标记。谢谢