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 "..."? Link to comment https://forums.phpfreaks.com/topic/81955-solved-max-x-chars-on-search-form/ 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)); ?> Link to comment https://forums.phpfreaks.com/topic/81955-solved-max-x-chars-on-search-form/#findComment-416382 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 Link to comment https://forums.phpfreaks.com/topic/81955-solved-max-x-chars-on-search-form/#findComment-416384 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') Link to comment https://forums.phpfreaks.com/topic/81955-solved-max-x-chars-on-search-form/#findComment-416386 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 Link to comment https://forums.phpfreaks.com/topic/81955-solved-max-x-chars-on-search-form/#findComment-416387 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.