PHP: properly truncating strings with “..”

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

    Just check the length to see if it's more than 30 characters or not:

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

    The typographic nitpick in me has this to add: the correct character to use is the ellipsis which comprises this character , three dots ..., or its HTML entity .

提交回复
热议问题