Page 1 of 1

substr based on strlen

Posted: Fri Jul 11, 2003 4:59 pm
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?

Posted: Fri Jul 11, 2003 5:21 pm
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));

Posted: Fri Jul 11, 2003 5:24 pm
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.

Posted: Fri Jul 11, 2003 6:38 pm
by ejason
Perfect, thanks :)