【问题标题】:PHP htmlentities allow <b> and <i> onlyPHP htmlentities 只允许 <b> 和 <i>
【发布时间】:2012-04-06 01:43:40
【问题描述】:

使用htmlentities() 是否可以设置为仅允许&lt;b&gt;&lt;i&gt; 转换为粗体和斜体文本?我知道有一种方法可以做到这一点,但我忘记了。

【问题讨论】:

    标签: php tags html-entities


    【解决方案1】:

    很简单

    <?php
    $string = htmlentities($text);
    $string = str_replace(array("&lt;i&gt;", "&lt;b&gt;", "&lt;/i&gt;", "&lt;/b&gt;"), array("<i>", "<b>", "</i>", "</b>"), $string);
    

    【讨论】:

    • 谢谢,但这将 和 留在字符串的末尾,当我尝试添加它来替换它们时,它不起作用:\
    • @Dylan 当然,我忘记了结束标签。立即尝试
    【解决方案2】:

    我使用辅助函数:

    #   Sanitizer function - removes forbidden tags, including script tags
    function strip_tags_attributes( $str, 
        $allowedTags = array('<a>','<b>','<blockquote>','<br>','<cite>','<code>','<del>','<div>','<em>','<ul>','<ol>','<li>','<dl>','<dt>','<dd>','<img>','<ins>','<u>','<q>','<h3>','<h4>','<h5>','<h6>','<samp>','<strong>','<sub>','<sup>','<p>','<table>','<tr>','<td>','<th>','<pre>','<span>'), 
        $disabledEvents = array('onclick','ondblclick','onkeydown','onkeypress','onkeyup','onload','onmousedown','onmousemove','onmouseout','onmouseover','onmouseup','onunload') )
    {       
        if( empty($disabledEvents) ) {
            return strip_tags($str, implode('', $allowedTags));
        }
        return preg_replace('/<(.*?)>/ies', "'<' . preg_replace(array('/javascript:[^\"\']*/i', '/(" . implode('|', $disabledEvents) . ")=[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", strip_tags($str, implode('', $allowedTags)));
    }
    

    对于您的示例,从 $allowedTags 数组中删除除 &lt;b&gt;&lt;i&gt; 之外的所有内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      • 2011-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多