Skip to content

Instantly share code, notes, and snippets.

@FiXato
Created March 27, 2009 00:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FiXato/86454 to your computer and use it in GitHub Desktop.
Save FiXato/86454 to your computer and use it in GitHub Desktop.
php multibyte wordwrap function that supports sentences.
<?php
// Adonis from Chat4All needed a multibyte wordwrap function that support multiple words,
// So based on some code from php.net I hacked together the following function.
// It's not pretty, but it works. It is supposed to be combined with a simple bbcode parser.
/*
* Based on code by Matt at newbiewebdevelopment dot idk
* http://nl2.php.net/manual/en/function.wordwrap.php#89369
* Adapted to support multiple words by Filip H.F. "FiXato" Slagter,
* http://github.com/FiXato
*
*/
function mb_wordwrap($string, $width=75, $break="\n", $cut = false) {
$words = explode(' ',$string);
foreach($words as &$word) {
if (!$cut) {
$regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.',}\b#U';
} else {
$regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.'}#';
}
$string_length = mb_strlen($word,'UTF-8');
$cut_length = ceil($string_length / $width);
$i = 1;
$new_word = '';
while ($i < $cut_length) {
preg_match($regexp, $word,$matches);
$new_string = $matches[0];
$new_word .= $new_string.$break;
$word = substr($word, strlen($new_string));
$i++;
}
$word = $new_word.$word;
}
return join(' ',$words);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment