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
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;
}
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 …
.
Add a strlen()
condition?
if (strlen($message) > 30) {
echo substr($message, 0, 30) . "..";
} else {
echo $message;
}
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;
}