PHP: properly truncating strings with “..”

前端 未结 6 1684
遇见更好的自我
遇见更好的自我 2021-02-07 08:59

Currently, the method I use to truncate strings is: echo substr($message, 0, 30).\"..\";

How do I show the dots only in the case that the string has been tr

6条回答
  •  轮回少年
    2021-02-07 09:40

    You could do:

    echo strlen($message) > 30 ? substr($message, 0, 30) . '..' : $mssage;
    

    Basically, it's like (but shorter):

    if (strlen($message) > 30) {
        echo substr($message, 0, 30) . "..";
    } else {
        echo $message;
    }
    

提交回复
热议问题