Overbleed Posted October 24, 2010 Share Posted October 24, 2010 Hey guys, I have a quick question. Im going to be making a script that will output the name of a news article along with the poster's name beside it. There is only a certain amount of space where that stuff can go so I want to know how I can make it so that say after 20 characters, it ends and puts "..." beside it. Is this possible with php? How would I do it? Quote Link to comment Share on other sites More sharing options...
wannabephpdude Posted October 24, 2010 Share Posted October 24, 2010 You're looking for substr() my man. See the following: substr() <?php echo substr('abcdef', 0, 4); // abcd ?> Quote Link to comment Share on other sites More sharing options...
PaulRyan Posted October 24, 2010 Share Posted October 24, 2010 Yes that is the correct route WPD but you have to consider cutting a word in half, so you would want to end on a space to keep formality. The following function does just that... <?php function cut_str($string){ $maxLength = 20; $suffix = '...'; $finalStr = ''; if(strlen($string) > $maxLength) { while($string{$maxLength} != ' '){ $finalStr .= $str{$maxLength}; $maxLength++; } return substr($string,0,$maxLength).$suffix; } else { return $string; } } $postTitle = 'This is my post title, just a filler really.'; echo cut_str($postTitle); ?> Tell me how it goes OverBleed Regards, Paul. Quote Link to comment Share on other sites More sharing options...
wannabephpdude Posted October 24, 2010 Share Posted October 24, 2010 Or... something like this for a bit more expandability. Overbleed, what this means is that you can set the maxLength for each use of this function. <?php function cut_str($maxLength,$string){ $suffix = '...'; $finalStr = ''; if(strlen($string) > $maxLength) { while($string{$maxLength} != ' '){ $finalStr .= $str{$maxLength}; $maxLength++; } return substr($string,0,$maxLength).$suffix; } else { return $string; } } $postTitle = 'This is my post title, just a filler really.'; echo cut_str(23,$postTitle); ?> Max length is now set to 23 and the result becomes => "This is my post title, just..." [edit] Nice code Paul ^5! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.