5
4

2 回答 2

12

这很容易

<?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);
于 2012-04-06T01:46:07.650 回答
6

我使用一个辅助函数:

#   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)));
}

对于您的示例,从数组中删除除<b>和之外的所有内容。<i>$allowedTags

于 2012-04-06T01:50:54.117 回答