富文本编辑器html过滤

需求是:允许特定的标签和属性入库

$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);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值