Limit # of characters

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
vchris
Forum Contributor
Posts: 204
Joined: Tue Aug 30, 2005 7:53 pm
Location: Canada, Quebec

Limit # of characters

Post 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?
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post by Skara »

Code: Select all

$txt = (strlen($txt) > 40) ? substr($txt,0,20).'...' : $txt;
Charles256
DevNet Resident
Posts: 1375
Joined: Fri Sep 16, 2005 9:06 pm

Post by Charles256 »

heh.loving that ternary aren't ya?:)
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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:
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post 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. ;)
Charles256
DevNet Resident
Posts: 1375
Joined: Fri Sep 16, 2005 9:06 pm

Post 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.
vchris
Forum Contributor
Posts: 204
Joined: Tue Aug 30, 2005 7:53 pm
Location: Canada, Quebec

Post by vchris »

Thanks buddy. works perfectly! :)
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post 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().
vchris
Forum Contributor
Posts: 204
Joined: Tue Aug 30, 2005 7:53 pm
Location: Canada, Quebec

Post 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.
Post Reply