需求是:允许特定的标签和属性入库
$result = '<h1>卡手机的风口浪尖爱上了对方就哭了</h1><h1>ddsadsadas</h1><div style="asdas" οnlοad="alert(1);"><font color="#39b54a" οnlοad="alert(1);">as<script>alert(1);</script>dfasdfasdf</font></div><div style="text-align: center">dsafadsfsda</div> ';
var_dump($result);
function filterRichText($desc)
{
$htmlTags = [
'b',
'strong',
'i',
'u',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'font',
'div',
'p',
];
$attributes = [
'style',
'color',
];
/*
* 不存在< >括号,则直接转义返回即可了
*/
if (strpos($desc, '<') === false || strpos($desc, '>') === false) {
return $desc;
}
/*
* 去掉没有匹配的后缀标签
*/
preg_match_all('/<([a-za-z1-9]+)([^>]*)>/', $desc, $matchs);
$tagsAll = $matchs[0];
$tags = $matchs[1];
static $yclTags = [];
foreach ($tagsAll as $i => $match) {
if (!empty($yclTags) && in_array($match, $yclTags)) {
continue;
}
if (!in_array($tags[$i], $htmlTags)) {
$patten = '/'.addslashesTag($match).'(.*?)<\/'.$tags[$i].'>/';
$desc = preg_replace_callback($patten, function ($m) {
return $m[1];
}, $desc);
}
if (!empty($matchs[2][$i])) {
$attributeArr = explode('"', $matchs[2][$i]);
$attributeArr = array_filter($attributeArr);
$attr = [];
foreach ($attributeArr as $value) {
if ($value != '/' && strpos($value, '=') !== false) {
$arr = explode('=', $value);
if (is_string($arr[0])) {
$attr[] = trim($arr[0]);
}
}
}
if (!empty($attr) && array_diff($attr, $attributes)) {
$patten = '/'.addslashesTag($match).'(.*?)<\/'.$tags[$i].'>/';
$desc = preg_replace_callback($patten, function ($m) {
return $m[1];
}, $desc);
}
}
$yclTags[] = $match;
}
return $desc;
}
function addslashesTag($match)
{
return str_replace(['(', ')'], ['\(', '\)'], $match);
}
$result = filterRichText($result);
var_dump($result);