note 100493 added to function.wordwrap
| From: | 1therion at osu1 dot php dot net | Date: | Tue, 19 Oct 2010 14:56:23 +0000 |
| Subject: | note 100493 added to function.wordwrap | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-173283@lists.php.net to get a copy of this message | ||
@Sam B
There is a bug in function You wrote. It lose some chars after break. Here is corrected version:
<?php
/**
* Multibyte capable wordwrap
*
* @param string $str
* @param int $width
* @param string $break
* @return string
*/
function mb_wordwrap($str, $width=74, $break="\r\n")
{
// Return short or empty strings untouched
if(empty($str) || mb_strlen($str, 'UTF-8') <= $width)
return $str;
$br_width = mb_strlen($break, 'UTF-8');
$str_width = mb_strlen($str, 'UTF-8');
$return = '';
$last_space = false;
for($i=0, $count=0; $i < $str_width; $i++, $count++)
{
// If we're at a break
if (mb_substr($str, $i, $br_width, 'UTF-8') == $break)
{
$count = 0;
$return .= mb_substr($str, $i, $br_width, 'UTF-8');
$i += $br_width - 1;
continue;
}
// Keep a track of the most recent possible break point
if(mb_substr($str, $i, 1, 'UTF-8') == " ")
{
$last_space = $i;
}
// It's time to wrap
if ($count > $width)
{
// There are no spaces to break on! Going to truncate :(
if(!$last_space)
{
$return .= $break;
$count = 0;
}
else
{
// Work out how far back the last space was
$drop = $i - $last_space;
// Cutting zero chars results in an empty string, so don't do that
if($drop > 0)
{
$return = mb_substr($return, 0, -$drop);
}
// Add a break
$return .= $break;
// Update pointers
$i = $last_space; //change here - we iterate the original text - there is no break
chars there
$last_space = false;
$count = 0;
}
}
// Add character from the input string to the output
$return .= mb_substr($str, $i, 1, 'UTF-8');
}
return $return;
}
?>
----
Server IP: 195.114.0.19
Probable Submitter: 95.51.9.10
----
Manual Page -- http://www.php.net/manual/en/function.wordwrap.php
Edit -- https://master.php.net/note/edit/100493
Del: integrated -- https://master.php.net/note/delete/100493/integrated
Del: useless -- https://master.php.net/note/delete/100493/useless
Del: bad code -- https://master.php.net/note/delete/100493/bad+code
Del: spam -- https://master.php.net/note/delete/100493/spam
Del: non-english -- https://master.php.net/note/delete/100493/non-english
Del: in docs -- https://master.php.net/note/delete/100493/in+docs
Del: other reasons-- https://master.php.net/note/delete/100493
Reject -- https://master.php.net/note/reject/100493
Search -- https://master.php.net/manage/user-notes.php