Close open HTML tags in a string

后端 未结 9 1951
南方客
南方客 2020-11-28 11:21

Situation is a string that results in something like this:

This is some text and here is a bold text then the post stop here....

9条回答
  •  眼角桃花
    2020-11-28 11:56

    This PHP method always worked for me. It will close all un-closed HTML tags.

    function closetags($html) {
        preg_match_all('#<([a-z]+)(?: .*)?(?#iU', $html, $result);
        $openedtags = $result[1];
    
        preg_match_all('##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 .= '';
            } else {
                unset($closedtags[array_search($openedtags[$i], $closedtags)]);
            }
        }
        return $html;
    }
    

提交回复
热议问题