Get first n characters of a string

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

    To create within a function (for repeat usage) and dynamical limited length, use:

    function string_length_cutoff($string, $limit, $subtext = '...')
    {
        return (strlen($string) > $limit) ? substr($string, 0, ($limit-strlen(subtext))).$subtext : $string;
    }
    
    // example usage:
    echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26);
    
    // or (for custom substitution text
    echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26, '..');
    
    0 讨论(0)
  • 2020-11-22 13:21
    //The simple version for 10 Characters from the beginning of the string
    $string = substr($string,0,10).'...';
    

    Update:

    Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):

    $string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;
    

    So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'

    Update 2:

    Or as function:

    function truncate($string, $length, $dots = "...") {
        return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
    }
    

    Update 3:

    It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the wordwrap function:

    function truncate($string,$length=100,$append="…") {
      $string = trim($string);
    
      if(strlen($string) > $length) {
        $string = wordwrap($string, $length);
        $string = explode("\n", $string, 2);
        $string = $string[0] . $append;
      }
    
      return $string;
    }
    
    0 讨论(0)
  • 2020-11-22 13:22

    It's best to abstract you're code like so (notice the limit is optional and defaults to 10):

    print limit($string);
    
    
    function limit($var, $limit=10)
    {
        if ( strlen($var) > $limit )
        {
            return substr($string, 0, $limit) . '...';
        }
        else
        {
            return $var;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 13:24

    This functionality has been built into PHP since version 4.0.6. See the docs.

    echo mb_strimwidth('Hello World', 0, 10, '...');
    
    // outputs Hello W...
    

    Note that the trimmarker (the ellipsis above) are included in the truncated length.

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

    sometimes, you need to limit the string to the last complete word ie: you don't want the last word to be broken instead you stop with the second last word.

    eg: we need to limit "This is my String" to 6 chars but instead of 'This i..." we want it to be 'This..." ie we will skip that broken letters in the last word.

    phew, am bad at explaining, here is the code.

    class Fun {
    
        public function limit_text($text, $len) {
            if (strlen($text) < $len) {
                return $text;
            }
            $text_words = explode(' ', $text);
            $out = null;
    
    
            foreach ($text_words as $word) {
                if ((strlen($word) > $len) && $out == null) {
    
                    return substr($word, 0, $len) . "...";
                }
                if ((strlen($out) + strlen($word)) > $len) {
                    return $out . "...";
                }
                $out.=" " . $word;
            }
            return $out;
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 13:29

    $width = 10;

    $a = preg_replace ("~^(.{{$width}})(.+)~", '\\1…', $a);
    

    or with wordwrap

    $a = preg_replace ("~^(.{1,${width}}\b)(.+)~", '\\1…', $a);
    
    0 讨论(0)
提交回复
热议问题