Created
March 27, 2009 00:03
-
-
Save FiXato/86454 to your computer and use it in GitHub Desktop.
php multibyte wordwrap function that supports sentences.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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