By admin, 1 year and 10 months ago
Format long texts
/** * Cut a text so it won't have more than $max_length chars and any word should not have more than $max_word chars * * @param unknown_type $length_limit * @param unknown_type $length_word */function format_long_text($str, $max_length=99999, $max_word = 60){ //limit string length $has_tail = false; if(strlen($str) > $max_length){ $new_str = substr($str, 0, $max_length); //search for non-alpha char for($i = $max_length; $i < strlen($str) && ctype_alpha($str[$i]); $i++) $new_str .= $str[$i]; $str = $new_str; $has_tail = true; }
if(3 < $max_word && $max_word < $max_length){ do{ $words = explode(' ', $str); $do_loop = false; foreach ($words as $word){
if(strlen($word) > $max_word){ //bug in IE: point followed by char does not split the text $fixed_word = str_replace('.', '. ', $word);
$new_word = ''; $j = 0; for($i = 0; $i < strlen($fixed_word); $i++){ $j = (' ' == $fixed_word[$i]?0:$j+1);
if(($j+1)%$max_word==0){ $new_word .= ' ' . $fixed_word[$i]; }else{ $new_word .= $fixed_word[$i]; } } $str = str_replace($word, $new_word, $str); $do_loop = true; break; } } }while($do_loop); }
return $str . ($has_tail?'..':'');}
No comments
Be the first to write a comment on this post.
Write a comment
If you want to add your comment on this post, simply fill out the next form:
You have to be logged-in to write a comment: (Log-in).
No trackbacks
To notify a mention on this post in your blog, enable automated notification (Options > Discussion in WordPress) or specify this trackback url: http://www.tai.ro/2008/04/16/format-long-texts/trackback/