使用htmlentities()
是否可以设置为仅允许<b>
和<i>
转换为粗体和斜体文字?我知道有一种方法可以做到这一点,但我已经忘记了。
答案 0 :(得分:10)
这很容易
<?php
$string = htmlentities($text);
$string = str_replace(array("<i>", "<b>", "</i>", "</b>"), array("<i>", "<b>", "</i>", "</b>"), $string);
答案 1 :(得分: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
之外的所有内容。