Reputation: 18103
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?
Upvotes: 18
Views: 16249
Reputation: 7672
if (strlen($message) > 30) {
echo substr($message, 0, 30) . "..";
} else {
echo $message;
}
Upvotes: 6
Reputation: 42360
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;
}
Upvotes: 6
Reputation: 138
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;
Upvotes: 6
Reputation: 724192
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 …
.
Upvotes: 22
Reputation: 165261
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;
}
Upvotes: 2