Shorten text without splitting words or breaking html tags

前端 未结 8 1356
粉色の甜心
粉色の甜心 2020-12-28 17:06

I am trying to cut off text after 236 chars without cutting words in half and preserving html tags. This is what I am using right now:

$shortdesc = $_helper-         


        
8条回答
  •  旧时难觅i
    2020-12-28 17:35

    function limitStrlen($input, $length, $ellipses = true, $strip_html = true, $skip_html) 
    {
        // strip tags, if desired
        if ($strip_html || !$skip_html) 
        {
            $input = strip_tags($input);
    
            // no need to trim, already shorter than trim length
            if (strlen($input) <= $length) 
            {
                return $input;
            }
    
            //find last space within length
            $last_space = strrpos(substr($input, 0, $length), ' ');
            if($last_space !== false) 
            {
                $trimmed_text = substr($input, 0, $last_space);
            } 
            else 
            {
                $trimmed_text = substr($input, 0, $length);
            }
        } 
        else 
        {
            if (strlen(strip_tags($input)) <= $length) 
            {
                return $input;
            }
    
            $trimmed_text = $input;
    
            $last_space = $length + 1;
    
            while(true)
            {
                $last_space = strrpos($trimmed_text, ' ');
    
                if($last_space !== false) 
                {
                    $trimmed_text = substr($trimmed_text, 0, $last_space);
    
                    if (strlen(strip_tags($trimmed_text)) <= $length) 
                    {
                        break;
                    }
                } 
                else 
                {
                    $trimmed_text = substr($trimmed_text, 0, $length);
                    break;
                }
            }
    
            // close unclosed tags.
            $doc = new DOMDocument();
            $doc->loadHTML($trimmed_text);
            $trimmed_text = $doc->saveHTML();
        }
    
        // add ellipses (...)
        if ($ellipses) 
        {
            $trimmed_text .= '...';
        }
    
        return $trimmed_text;
    }
    
    $str = "

    Lorem ipsum

    dolor

    sit amet, consetetur.

    "; // view the HTML echo htmlentities(limitStrlen($str, 22, false, false, true), ENT_COMPAT, 'UTF-8'); // view the result echo limitStrlen($str, 22, false, false, true);

    Note: There may be a better way to close tags instead of using DOMDocument. For example we can use a p tag inside a h1 tag and it still will work. But in this case the heading tag will close before the p tag because theoretically it's not possible to use p tag inside it. So, be careful for HTML's strict standards.

提交回复
热议问题