【问题标题】:htmlentities with exceptionshtmlentities 有例外
【发布时间】:2010-11-06 17:45:08
【问题描述】:

我有一些可能的标签,例如"<main>", "<text>", "<tag>"。我想用 htmlentities (htmlspecialchars) 处理的其余字符

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

结果应该是

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

最好的方法是什么。

【问题讨论】:

    标签: php xml special-characters


    【解决方案1】:

    您可以在文本上运行 htmlentities,然后使用正则表达式替换允许的标签 &lt;&gt;

    示例...

    $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 );
    

    【讨论】:

    • 您在括号外留下了 $v。
    • 我也认为&gt; 可以在属性值中使用。 (我不确定。)
    • 您可以在属性值中包含&gt;。所以正则表达式并非在所有情况下都有效。
    • 它将 更改为
    【解决方案2】:

    我看到的唯一解决方案是将其加载到 XML 解析器中,然后自己递归构建输出字符串,但这需要一些工作。

    注意:正则表达式解决方案(如 Galen 建议的)并非在所有情况下都有效,因为属性值可能包含 &gt;

    【讨论】:

      【解决方案3】:

      我有一个对我有用的简单解决方案:

      $text = htmlentities($text, ENT_QUOTES, "UTF-8");
      $text = htmlspecialchars_decode($text);
      $text = strip_tags($text, "<p><b><h2>");
      

      【讨论】:

        猜你喜欢
        • 2020-09-30
        • 2014-08-26
        • 2011-09-10
        • 1970-01-01
        • 2010-09-07
        • 1970-01-01
        • 2012-01-16
        • 1970-01-01
        • 2011-06-21
        相关资源
        最近更新 更多