/**
* 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?'..':'');
}
Snippet codes and other stuff good to remember. Various source codes, tips and other things I encountered while working
Tuesday, July 31, 2007
Format long texts
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment