Northern Flame Posted December 16, 2007 Share Posted December 16, 2007 I have a search form which works fine, when a user searches for something it displays the results in this format TITLE DESCRIPTION LINK(click here to read more) but sometimes the description is too long and it stretches out my template, how can I set the limit for the maximum amount of characters allowed to be displayed from my description and after the maximum characters echo "..."? Quote Link to comment Share on other sites More sharing options...
Daniel0 Posted December 16, 2007 Share Posted December 16, 2007 Something like this? <?php function truncate($string, $max_chars = 30) { if(strlen($string) > $max_chars) { $string = substr($string, 0, $max_chars).'...'; } return $string; } echo truncate(str_repeat('abc', 20)); ?> Quote Link to comment Share on other sites More sharing options...
Northern Flame Posted December 16, 2007 Author Share Posted December 16, 2007 thanks Daniel0 I just tested it out, but it works better if you replace the 20 with 1 <?php function truncate($string, $max_chars = 30) { if(strlen($string) > $max_chars) { $string = substr($string, 0, $max_chars).'...'; } return $string; } echo truncate(str_repeat('abc', 1)); ?> this way it doesnt repeat my text 20 times lol Quote Link to comment Share on other sites More sharing options...
Daniel0 Posted December 16, 2007 Share Posted December 16, 2007 The str_repeat() was just to get a string long enough to be truncated. I just didn't bother to to type a lot of characters so I had PHP do it for me. You'd just use it like this: truncate('long text here') Quote Link to comment Share on other sites More sharing options...
Northern Flame Posted December 16, 2007 Author Share Posted December 16, 2007 oh alright thanks for the help 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.