Page 1 of 1

Limit # of characters

Posted: Sat Sep 24, 2005 3:40 pm
by vchris
Hi,

I want to limit the number of characters when displaying a record. For example, if the record is 40 characters long I want to stop it at 20 and add "..." at the end because some URLs can be very long.

How would I do that?

Posted: Sat Sep 24, 2005 3:43 pm
by Skara

Code: Select all

$txt = (strlen($txt) > 40) ? substr($txt,0,20).'...' : $txt;

Posted: Sat Sep 24, 2005 3:44 pm
by Charles256
heh.loving that ternary aren't ya?:)

Posted: Sat Sep 24, 2005 3:45 pm
by John Cartwright

Code: Select all

function chopLink($url, $length='20') {
   return strlen($url >= $length) ? '<a href="'.$url.'">'.substr($url,0,$length).'...</a>' : '<a href="'.$url.'">'.$url'</a>';
}
edit | too late :roll:

Posted: Sat Sep 24, 2005 3:47 pm
by Skara
Charles256 wrote:heh.loving that ternary aren't ya?:)
I'm obsessed with taking up as few lines as possible. ^^;
In this case, though, a ternary makes perfect sense. ;)

Posted: Sat Sep 24, 2005 3:47 pm
by Charles256
i'm obsessed with reading my file as ifit were enlish:-D so I RARELY use the ternary operand. but i guess it's all personal preference.

Posted: Sat Sep 24, 2005 3:48 pm
by vchris
Thanks buddy. works perfectly! :)

Posted: Sat Sep 24, 2005 3:49 pm
by John Cartwright
I often use ternary for setting default variables.

Code: Select all

$var = isset($_GET['pagenum']) : $_GET['pagenum'] : 0;
Often helps with unitialized variables

Posted: Sat Sep 24, 2005 3:50 pm
by Skara
No problem, vchris. ;)
Charles256 wrote:i'm obsessed with reading my file as ifit were enlish:-D so I RARELY use the ternary operand. but i guess it's all personal preference.
Haha, I can read code near as easily as I can English. :P (my own code, anyway)

@jcart: I've just gotten into a habit of using isset() or empty().

Posted: Sat Sep 24, 2005 3:56 pm
by vchris
hahah... not yet for me. I just started PHP for this site but I already know asp, coldfusion, sql...

I find php cool but not as easy as coldfusion.