Get first n characters of a string

前端 未结 19 1526
萌比男神i
萌比男神i 2020-11-22 13:06

How can I get the first n characters of a string in PHP? What\'s the fastest way to trim a string to a specific number of characters, and append \'...\' if needed?

19条回答
  •  我在风中等你
    2020-11-22 13:14

    The codeigniter framework contains a helper for this, called the "text helper". Here's some documentation from codeigniter's user guide that applies: http://codeigniter.com/user_guide/helpers/text_helper.html (just read the word_limiter and character_limiter sections). Here's two functions from it relevant to your question:

    if ( ! function_exists('word_limiter'))
    {
        function word_limiter($str, $limit = 100, $end_char = '…')
        {
            if (trim($str) == '')
            {
                return $str;
            }
    
            preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);
    
            if (strlen($str) == strlen($matches[0]))
            {
                $end_char = '';
            }
    
            return rtrim($matches[0]).$end_char;
        }
    }
    

    And

    if ( ! function_exists('character_limiter'))
    {
        function character_limiter($str, $n = 500, $end_char = '…')
        {
            if (strlen($str) < $n)
            {
                return $str;
            }
    
            $str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));
    
            if (strlen($str) <= $n)
            {
                return $str;
            }
    
            $out = "";
            foreach (explode(' ', trim($str)) as $val)
            {
                $out .= $val.' ';
    
                if (strlen($out) >= $n)
                {
                    $out = trim($out);
                    return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
                }       
            }
        }
    }
    

提交回复
热议问题