PHP: properly truncating strings with “..”

前端 未结 6 1608
遇见更好的自我
遇见更好的自我 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:25

    It should be noted that the strlen() function does not count characters, it counts bytes. If you are using UTF-8 encoding you may end up with 1 character that is counted as up to 4 bytes. The proper way to do this would be something like:

    echo mb_strlen($message) > 30 ? mb_substr($message, 0, 30) . "..." : $message;
    

提交回复
热议问题