tags:

views:

50

answers:

5
+2  Q: 

PHP: substr ".."

So i have echo substr($message, 0, 30).".."; this line right now. As you can see the two dots after, is to show that there´s more and it has been cutted down to 30 chars, but how do i do so ONLY if it has been cutted down to 30 chars then it should echo the dots ".." else then dont show ".."

+4  A: 

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

BoltClock
Ha! You were 18 seconds quicker :)
sprain
+1 because use of …
fabrik
(Especially @fabrik and whoever who voted him up:) Using named entities in HTML is deprecated – don’t do it, since (modern!) browsers will choke on it when used together with XHTML. A better solution is always to use the character directly, along with a correct encoding, i.e. UTF-8 or similar. But +1 for mentioning the correct symbol nonetheless.
Konrad Rudolph
@Konrad Rudolph: thanks! Seems I haven't been in the loop about the deprecation. Fixed my answer!
BoltClock
Thanks Konrad, that was new for me!
fabrik
+2  A: 
if (strlen($message) > 30) {
 echo substr($message, 0, 30)."..";
} else {
 echo $message;
}
GSto
+1  A: 
if(strlen($message) > 30){
  echo substr($message, 0, 30)."..";
}else{
  echo $message;
}

Cheers!

sprain
A: 

Add a strlen() condition?

Col. Shrapnel
+1  A: 

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;
}
ircmaxell
shorter but it's barbarian language, unlike plain and simple English `if str[ing] len[gth] [of the] message more than 30...`
Col. Shrapnel
True, but I like the ternary syntax for this kind of thing. It's shorter and more to the point. It also is the textbook scenario for its usage (branching logic with the same "outcome" with both branches)...
ircmaxell