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

前端 未结 11 1867
我在风中等你
我在风中等你 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:11

    I would go with Pascal MARTIN's answer, with some additional improvements. Because;

    1 - "PHP wordwrap", respects word boundaries automatically

    2 - If your string contains a word more than 25 chars(aagh, so there is nothing to do) you can force "PHP wordwrap" to cut word.(improvement)

    3 - If your string is shorter than 25 chars, then "..." will seem ugly after a complete sentence.(improvement)

    $str = "This string might be longer than 25 chars, or might not!";
    // we are forcing to cut long words...
    $wrapped = wordwrap($str, 25, "\n", 1);
    var_dump($wrapped);
    
    $lines = explode("\n", $wrapped);
    var_dump($lines);
    
    // if our $str is shorter than 25, there will be no $lines[1]
    (array_key_exists('1', $lines)) ? $suffix = '...' : $suffix = '';
    $new_str = $lines[0] . $suffix;
    var_dump($new_str);
    

提交回复
热议问题