Sunday, April 24, 2016

Php script to to close unclosed HTML tags in text

When displaying the few words or characters of a post,
we usually use
 
echo substr($string,0,numberOfChars);


The problem is that if the text was extracted from a rich edited post, some unclosed tags will impact the display of your site, since the extracted characters may contain unclosed HTML tags.

The solution is to use that little code found at
http://stackoverflow.com/questions/3059398/how-to-close-unclosed-html-tags
written by
https://stackoverflow.com/users/342999/kamal

That's great

 
function closetags($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;

}