note 103582 deleted from function.wordwrap by danbrown
| From: | danbrown@php.net | Date: | Thu, 21 Apr 2011 16:02:53 +0000 |
| Subject: | note 103582 deleted from function.wordwrap by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-179051@lists.php.net to get a copy of this message | ||
Note Submitter: benallfree at gmail dot com
----
Bug fix to previous version which did not account for <br> tags in HTML introducing a visible
space.
function htmlwrap(&$str, $maxLength=70, $char="<br />\n"){
$count = 0;
$newStr = '';
$openTag = false;
$lenstr = strlen($str);
$last_tag = "";
for($i=0; $i<$lenstr; $i++){
$newStr .= $str{$i};
if($openTag) $last_tag.=$str{$i};
if($str{$i} == '<'){
$last_tag = "<";
$openTag = true;
continue;
}
if(($openTag) && ($str{$i} == '>')){
$openTag = false;
if(preg_match("/^<\s*br\s*/", $last_tag)!=0)
{
$lastspace=0;
$count=0;
}
continue;
}
if(!$openTag){
if($str{$i} == ' '){
if ($count == 0) {
$newStr = substr($newStr,0, -1);
continue;
} else {
$lastspace = $count + 1;
}
}
$count++;
if($count==$maxLength){
if ($str{$i+1} != ' ' && $lastspace && ($lastspace <
$count)) {
$tmp = ($count - $lastspace)* -1;
$newStr = substr($newStr,0, $tmp) . $char . substr($newStr,$tmp);
$count = $tmp * -1;
} else {
$newStr .= $char;
$count = 0;
$lastspace = 0;
}
}
}
}
return $newStr;
}