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 ".."
views:
50answers:
5
+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
2010-08-17 13:30:22
Ha! You were 18 seconds quicker :)
sprain
2010-08-17 13:31:16
+1 because use of …
fabrik
2010-08-17 13:32:07
(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
2010-08-17 13:37:37
@Konrad Rudolph: thanks! Seems I haven't been in the loop about the deprecation. Fixed my answer!
BoltClock
2010-08-17 13:41:22
Thanks Konrad, that was new for me!
fabrik
2010-08-17 14:18:49
+2
A:
if (strlen($message) > 30) {
echo substr($message, 0, 30)."..";
} else {
echo $message;
}
GSto
2010-08-17 13:30:26
+1
A:
if(strlen($message) > 30){
echo substr($message, 0, 30)."..";
}else{
echo $message;
}
Cheers!
sprain
2010-08-17 13:30:40
+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
2010-08-17 13:31:30
shorter but it's barbarian language, unlike plain and simple English `if str[ing] len[gth] [of the] message more than 30...`
Col. Shrapnel
2010-08-17 13:33:52
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
2010-08-17 13:42:01