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

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

    To avoid cutting right in the middle of a word, you might want to try the wordwrap function ; something like this, I suppose, could do :

    $str = "this is a long string that should be cut in the middle of the first 'that'";
    $wrapped = wordwrap($str, 25);
    var_dump($wrapped);
    
    $lines = explode("\n", $wrapped);
    var_dump($lines);
    
    $new_str = $lines[0] . '...';
    var_dump($new_str);
    

    $wrapped will contain :

    string 'this is a long string
    that should be cut in the
    middle of the first
    'that'' (length=74)
    

    The $lines array will be like :

    array
      0 => string 'this is a long string' (length=21)
      1 => string 'that should be cut in the' (length=25)
      2 => string 'middle of the first' (length=19)
      3 => string ''that'' (length=6)
    

    And, finally, your $new_string :

    string 'this is a long string' (length=21)
    


    With a substr, like this :

    var_dump(substr($str, 0, 25) . '...');
    

    You'd have gotten :

    string 'this is a long string tha...' (length=28)
    

    Which doesn't look that nice :-(


    Still, have fun !

提交回复
热议问题