【发布时间】:2012-04-06 01:43:40
【问题描述】:
使用htmlentities() 是否可以设置为仅允许<b> 和<i> 转换为粗体和斜体文本?我知道有一种方法可以做到这一点,但我忘记了。
【问题讨论】:
标签: php tags html-entities
使用htmlentities() 是否可以设置为仅允许<b> 和<i> 转换为粗体和斜体文本?我知道有一种方法可以做到这一点,但我忘记了。
【问题讨论】:
标签: php tags html-entities
很简单
<?php
$string = htmlentities($text);
$string = str_replace(array("<i>", "<b>", "</i>", "</b>"), array("<i>", "<b>", "</i>", "</b>"), $string);
【讨论】:
我使用辅助函数:
# 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 数组中删除除 <b> 和 <i> 之外的所有内容。
【讨论】: