Get first n characters of a string

前端 未结 19 1118
萌比男神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:13

    If you want to cut being careful to don't split words you can do the following

    function ellipse($str,$n_chars,$crop_str=' [...]')
    {
        $buff=strip_tags($str);
        if(strlen($buff) > $n_chars)
        {
            $cut_index=strpos($buff,' ',$n_chars);
            $buff=substr($buff,0,($cut_index===false? $n_chars: $cut_index+1)).$crop_str;
        }
        return $buff;
    }
    

    if $str is shorter than $n_chars returns it untouched.

    If $str is equal to $n_chars returns it as is as well.

    if $str is longer than $n_chars then it looks for the next space to cut or (if no more spaces till the end) $str gets cut rudely instead at $n_chars.

    NOTE: be aware that this method will remove all tags in case of HTML.

    0 讨论(0)
  • 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;
                }       
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 13:14

    Use substring

    http://php.net/manual/en/function.substr.php

    $foo = substr("abcde",0, 3) . "...";
    
    0 讨论(0)
  • 2020-11-22 13:14

    I'm not sure if this is the fastest solution, but it looks like it is the shortest one:

    $result = current(explode("\n", wordwrap($str, $width, "...\n")));
    

    P.S. See some examples here https://stackoverflow.com/a/17852480/131337

    0 讨论(0)
  • 2020-11-22 13:15

    I developed a function for this use

     function str_short($string,$limit)
            {
                $len=strlen($string);
                if($len>$limit)
                {
                 $to_sub=$len-$limit;
                 $crop_temp=substr($string,0,-$to_sub);
                 return $crop_len=$crop_temp."...";
                }
                else
                {
                    return $string;
                }
            }
    

    you just call the function with string and limite
    eg:str_short("hahahahahah",5);
    it will cut of your string and add "..." at the end
    :)

    0 讨论(0)
  • 2020-11-22 13:16

    substr() would be best, you'll also want to check the length of the string first

    $str = 'someLongString';
    $max = 7;
    
    if(strlen($str) > $max) {
       $str = substr($str, 0, $max) . '...';
    }
    

    wordwrap won't trim the string down, just split it up...

    0 讨论(0)
提交回复
热议问题