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 truncated?
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 …
.
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;
Just check the length of the original string to see if it needs to be truncated. If it is longer than 30, truncate the string and add the dots on the end:
if (strlen($message) > 30) {
echo substr($message, 0, 30)."..";
} else {
echo $message;
}
if (strlen($message) > 30) {
echo substr($message, 0, 30) . "..";
} else {
echo $message;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With