How to close unclosed HTML Tags?

后端 未结 8 605
名媛妹妹
名媛妹妹 2020-11-30 01:56

Whenever we are fetching some user inputed content with some editing from the database or similar sources, we might retrieve the portion which only contains the opening tag

8条回答
  •  一个人的身影
    2020-11-30 02:23

    A better PHP function to delete not open/not closed tags from webmaster-glossar.de (me)

    function closetag($html){
        $html_new = $html;
        preg_match_all ( "#<([a-z]+)( .*)?(?!/)>#iU", $html, $result1);
        preg_match_all ( "##iU", $html, $result2);
        $results_start = $result1[1];
        $results_end = $result2[1];
        foreach($results_start AS $startag){
            if(!in_array($startag, $results_end)){
                $html_new = str_replace('<'.$startag.'>', '', $html_new);
            }
        }
        foreach($results_end AS $endtag){
            if(!in_array($endtag, $results_start)){
                $html_new = str_replace('', '', $html_new);
            }
        }
        return $html_new;
    }
    

    use this function like:

    closetag('i love my cat'); 
    #output: i love my cat
    
    closetag('i love my cat'); 
    #output: i love my cat
    

提交回复
热议问题