How do you cut off text after a certain amount of characters in PHP?

前端 未结 11 1866
我在风中等你
我在风中等你 2021-02-02 12:22

I have two string that i want to limit to lets say the first 25 characters for example. Is there a way to cut off text after the 25th character and add a ... to the end of the s

相关标签:
11条回答
  • 2021-02-02 13:14

    May I make a modification to pallan's code?

    $truncated = (strlen($string) > 20) ? substr($string, 0, 20) . '...' : $string;
    

    This doesn't add the '...' if it is shorter.

    0 讨论(0)
  • 2021-02-02 13:15

    You're looking for the substr method.

    $s = substr($input, 0, 25);
    

    This will get you the first chuck of the string and then you can append whatever you'd like to the end.

    0 讨论(0)
  • 2021-02-02 13:17

    Really quickly,

    $truncated = substr('12345678901234567890abcdefg', 0, 20) . '...'
    
    0 讨论(0)
  • 2021-02-02 13:20

    This one is short and takes word boundary into account, it doesn't use loops which makes it very efficient

    function truncate($str, $chars, $end = '...') {
        if (strlen($str) <= $chars) return $str;
        $new = substr($str, 0, $chars + 1);
        return substr($new, 0, strrpos($new, ' ')) . $end;
    }
    

    Usage:

    truncate('My string', 5); //returns: My...
    
    0 讨论(0)
  • 2021-02-02 13:22
    <?php echo substr('12345678901234567890abcdefg', 0, 20) . '...' ?>
    

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

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