<?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; } ?>