Karem
Karem

Reputation: 18103

PHP: properly truncating strings with ".."

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

Answers (6)

sprain
sprain

Reputation: 7672

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

Upvotes: 6

GSto
GSto

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

beaudierman
beaudierman

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

BoltClock
BoltClock

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

ircmaxell
ircmaxell

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

Your Common Sense
Your Common Sense

Reputation: 157919

Add a strlen() condition?

Upvotes: 1

Related Questions