Another solution to utf-8 safe wordwrap, unsing regular expressions.
Pretty good performance and works in linear time.
<?php
function utf8_wordwrap($string, $width=75, $break="\n", $cut=false)
{
if($cut) {
$search = '/(.{1,'.$width.'})(?:\s|$)|(.{'.$width.'})/uS';
$replace = '$1$2'.$break;
} else {
$pattern = '/(?=\s)(.{1,'.$width.'})(?:\s|$)/uS';
$replace = '$1'.$break;
}
return preg_replace($search, $replace, $string);
}
?>
Of course don't forget to use preg_quote on the $width and $break parameters if they come from untrusted input.