donglu9743 2013-03-20 17:23
浏览 17
已采纳

如何用php关闭评论中的标签

In my application people are posting comments, and some times the user doesn't close the tags so it destroys all my layout.

I allow user to post html comment.

For example they post this way :

<center><b>Hello

So what I want is to close the tags on it and make it this way:

<center><b>Hello</b></center>

I searched on Google but din't find a good solution so I am here.

I tried this method but it does not work.

$yourText = $row['content'];

$doc = new DOMDocument();
$doc->loadHTML("$yourText");
$yourText = $doc->saveHTML();

Thanks.

  • 写回答

5条回答 默认 最新

  • doushou1298 2013-03-20 17:31
    关注

    You can use this function to close all the opened HTML tags in your content :

    function closeHtmlTags($html) {
    
        preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
        $openedtags = $result[1];
        preg_match_all('#</([a-z]+)>#iU', $html, $result);
        $closedtags = $result[1];
        $len_opened = count($openedtags);
    
        if (count($closedtags) == $len_opened) {
            return $html;
        }
        $openedtags = array_reverse($openedtags);
    
        for ($i=0; $i < $len_opened; $i++) {
            if (!in_array($openedtags[$i], $closedtags)) {
                $html .= '</'.$openedtags[$i].'>';
            } else {
                unset($closedtags[array_search($openedtags[$i], $closedtags)]);
            }
        }
    
        return $html;
    }
    

    Just call :

    $content = closeHtmlTags($content);
    

    This will return the content will all HTML tags close.

    Also you can use the PHP extension php_tidy

    $tidy = new Tidy();
    $content = $tidy->repairString($str, array(
        'output-xml' => true,
        'input-xml' => true
    ));
    

    Hope this helps

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图