Format long texts

Posted: April 16th, 2008 | Author: | Filed under: Developers | No Comments »


<pre lang="php">
<?php
/**
 * 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 int $length_limit
 * @param int $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{
      //$stripped_str = strip_tags($str);
      //$words = explode(' ', $stripped_str);
      $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?'..':'');
}
?>
</pre>



Leave a Reply