Word wrapping

wordwrap.inc.php
<?php
 
function mywordwrap($txt, $where, $tolerance = 2, $filter = array(' '=>true, '-'=>false, '/'=>false)) {
  $len = strlen($txt);
  $delta = $len-$where;
  if ($delta>$tolerance) {
    // string is longer than $where+$tolerance
    $final = array();
    $line = '';
    $linewords = 0;
 
    // create translation table
    $trans = array();
    foreach ($filter as $fitem=>$spaceafter) {
      $trans[$fitem] = (($spaceafter===false)?$fitem:'') . '#$#';
    }
 
    $txt = str_replace("\r\n", '#$#', $txt);
    $txt = str_replace("\r", '#$#', $txt);
    $txt = str_replace("\n", '#$#', $txt);
 
    $wordstmp = explode('#$#', strtr($txt, $trans));
 
    // remove empty elements and elements with spaces only
    $words = array();
    foreach ($wordstmp as $word) {
      $word = trim($word);
      if (!empty($word)) {
        $words[] = $word;
      }
    }
    $wordcount = count($words);
 
    for ($i=0;$i<$wordcount;$i++) {
      $chk = substr($line, -1);
      if (empty($line) || $filter[$chk] === false) { $spc = ''; } else { $spc = ' '; }
      $probe = $line . $spc . $words[$i];
      if (strlen($probe) > $where+$tolerance) {
        // with next word added, line would be too long
        if (!empty($line)) {
          $final[] = $line;
        }
        $line = $words[$i];
      } else {
        // word fits into current line
        $line = $probe;
        $linewords++;
      }
    }
    $final[] = $line;
    $txt = implode($final, "\n");
  }
  return $txt;
}
 
?>

 
snippets/php/wordwrap.txt · Last modified: 2010-01-15 14:36.36 by mbirth
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki Contents powered by Club-Mate Contents powered by BassDrive.com Labelled with ICRA