PHP substr but keep HTML tags?

后端 未结 3 915
不知归路
不知归路 2020-12-28 17:19

I am wondering if there is an elegant way to trim some text but while being HTML tag aware?

For example, I have this string:

$data = \'         


        
3条回答
  •  旧巷少年郎
    2020-12-28 17:49

    A few mounths ago I created a special function which is solution for your problem.

    Here is a function:

    function substr_close_tags($code, $limit = 300)
    {
        if ( strlen($code) <= $limit )
        {
            return $code;
        }
    
        $html = substr($code, 0, $limit);
        preg_match_all ( "#<([a-zA-Z]+)#", $html, $result );
    
        foreach($result[1] AS $key => $value)
        {
            if ( strtolower($value) == 'br' )
            {
                unset($result[1][$key]);
            }
        }
        $openedtags = $result[1];
    
        preg_match_all ( "##iU", $html, $result );
        $closedtags = $result[1];
    
        foreach($closedtags AS $key => $value)
        {
            if ( ($k = array_search($value, $openedtags)) === FALSE )
            {
                continue;
            }
            else
            {
                unset($openedtags[$k]);
            }
        }
    
        if ( empty($openedtags) )
        {
            if ( strpos($code, ' ', $limit) == $limit )
            {
                return $html."...";
            }
            else
            {
                return substr($code, 0, strpos($code, ' ', $limit))."...";
            }
        }
    
        $position = 0;
        $close_tag = '';
        foreach($openedtags AS $key => $value)
        {   
            $p = strpos($code, (''), $limit);
    
            if ( $p === FALSE )
            {
                $code .= ('');
            }
            else if ( $p > $position )
            {
                $close_tag = '';
                $position = $p;
            }
        }
    
        if ( $position == 0 )
        {
            return $code;
        }
    
        return substr($code, 0, $position).$close_tag."...";
    }
    

    Here is DEMO: http://sandbox.onlinephpfunctions.com/code/899d8137c15596a8528c871543eb005984ec0201 (click "Execute code" to check how it works).

提交回复
热议问题