如何使用 htmlspecialchars() 但将 <a> 标签与其他标签一起保留在 PHP 中?

How to use htmlspecialchars() but keep the <a> tag along with others in PHP?

我正在尝试使用 htmlspecialchars() 但想保留以下标签:

<a><b><i>.

我该怎么做?

我找到的解决方案似乎无法与属性标签和普通普通标签一起使用。

这是我发现的一段代码,应该允许带有属性的标签:

function fix_attributes($match){
    return "<".$match[1].str_replace('&quot;','"',$match[2]).">";
}
function allow_only($str, $allowed){
    $str = htmlspecialchars($str);
    foreach( $allowed as $a ){
        $str = preg_replace_callback("/&lt;(".$a."){1}([\s\/\.\w=&;:#]*?)&gt;/", fix_attributes, $str);
        $str = str_replace("&lt;/".$a."&gt;", "</".$a.">", $str);
    }
    return $str;
}
echo allow_only('This is <b>bold</b> and <a href="http://www.#links">this</a> is <i>italic</i>.', array("b","a","i"));

Source

但是,它一直给我一个错误:未定义常量的使用fix_attributes

如有任何帮助,我将不胜感激!

问题:使用不带引号的回调函数

有关详细信息,请参阅 http://php.net/manual/en/function.preg-replace-callback.php

 <?php
    function fix_attributes($match){
        return "<".$match[1].str_replace('&quot;','"',$match[2]).">";
    }
    function allow_only($str, $allowed){
        $str = htmlspecialchars($str);
        foreach( $allowed as $a ){
            $str = preg_replace_callback("/&lt;(".$a."){1}([\s\/\.\w=&;:#]*?)&gt;/", "fix_attributes", $str);//use quotes here 
            $str = str_replace("&lt;/".$a."&gt;", "</".$a.">", $str);
        }
        return $str;
    }
    echo allow_only('This is <b>bold</b> and <a href="http://www.#links">this</a> is <i>italic</i>.', array("b","a","i"));
    ?>