Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: properly truncating strings with ".."

Tags:

php

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?

like image 237
Karem Avatar asked Aug 17 '10 13:08

Karem


4 Answers

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 ….

like image 188
BoltClock Avatar answered Oct 31 '22 09:10

BoltClock


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;
like image 20
beaudierman Avatar answered Oct 31 '22 11:10

beaudierman


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;
}
like image 6
GSto Avatar answered Oct 31 '22 10:10

GSto


if (strlen($message) > 30) {
  echo substr($message, 0, 30) . "..";
} else {
  echo $message;
}
like image 6
sprain Avatar answered Oct 31 '22 11:10

sprain