Close open HTML tags in a string

后端 未结 9 1949
南方客
南方客 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:46

    A small modification to the original answer...while the original answer stripped tags correctly. I found that during my truncation, I could end up with chopped up tags. For example:

    This text has some in it
    

    Truncating at character 21 results in:

    This text has some <
    

    The following code, builds on the next best answer and fixes this.

    function truncateHTML($html, $length)
    {
        $truncatedText = substr($html, $length);
        $pos = strpos($truncatedText, ">");
        if($pos !== false)
        {
            $html = substr($html, 0,$length + $pos + 1);
        }
        else
        {
            $html = substr($html, 0,$length);
        }
    
        preg_match_all('#<(?!meta|img|br|hr|input\b)\b([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;
    }
    
    
    $str = "This text has bold in it";
    print "Test 1 - Truncate with no tag: " . truncateHTML($str, 5) . "
    \n"; print "Test 2 - Truncate at start of tag: " . truncateHTML($str, 20) . "
    \n"; print "Test 3 - Truncate in the middle of a tag: " . truncateHTML($str, 16) . "
    \n"; print "Test 4: - Truncate with less text: " . truncateHTML($str, 300) . "
    \n";

    Hope it helps someone out there.

提交回复
热议问题