substr based on strlen

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
ejason
Forum Newbie
Posts: 2
Joined: Fri Jul 11, 2003 4:59 pm
Location: Cleveland, OH

substr based on strlen

Post by ejason »

I'm working on an article system and I'm not really sure how to go about one part. I need to have a string truncated based on how long it is.

For example:

If the string is over 200 characters, cut to 100.
If the string is over 600 characters, cut to 300.
If the string is over 1200 characters, cut to 600.

So in usage, the longer the article the more text is shown on a preview before it gets truncated. Any suggestions?
qartis
Forum Contributor
Posts: 271
Joined: Sat Dec 14, 2002 4:43 pm
Location: BC, Canada
Contact:

Post by qartis »

Based on your examples, you want to show exactly half of a string. Like this:

Code: Select all

$string1="this string is 30 digits long.";
$string2 = substr($string1,0,(strlen($string1)/2));
qartis
Forum Contributor
Posts: 271
Joined: Sat Dec 14, 2002 4:43 pm
Location: BC, Canada
Contact:

Post by qartis »

Sorry for the double post..

If you want to do it in increments, go with a switch:

Code: Select all

switch (strlen($string)){
case 200:
$preview_text = substr($string,0,100);
break;
case 600:
$preview_text = substr($string,0,300);
break;
case 1200:
$preview_text = substr($string,0,600);
break;
}

Where $string is your article, and $preview_text will be the formatted preview message.
ejason
Forum Newbie
Posts: 2
Joined: Fri Jul 11, 2003 4:59 pm
Location: Cleveland, OH

Post by ejason »

Perfect, thanks :)
Post Reply