shared.mb_wordwrap.php (2474B)
1 <?php 2 /** 3 * Smarty shared plugin 4 * 5 * @package Smarty 6 * @subpackage PluginsShared 7 */ 8 9 if (!function_exists('smarty_mb_wordwrap')) { 10 11 /** 12 * Wrap a string to a given number of characters 13 * 14 * @link http://php.net/manual/en/function.wordwrap.php for similarity 15 * 16 * @param string $str the string to wrap 17 * @param int $width the width of the output 18 * @param string $break the character used to break the line 19 * @param boolean $cut ignored parameter, just for the sake of 20 * 21 * @return string wrapped string 22 * @author Rodney Rehm 23 */ 24 function smarty_mb_wordwrap($str, $width = 75, $break = "\n", $cut = false) 25 { 26 // break words into tokens using white space as a delimiter 27 $tokens = preg_split('!(\s)!S' . Smarty::$_UTF8_MODIFIER, $str, - 1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE); 28 $length = 0; 29 $t = ''; 30 $_previous = false; 31 $_space = false; 32 33 foreach ($tokens as $_token) { 34 $token_length = mb_strlen($_token, Smarty::$_CHARSET); 35 $_tokens = array($_token); 36 if ($token_length > $width) { 37 if ($cut) { 38 $_tokens = preg_split('!(.{' . $width . '})!S' . Smarty::$_UTF8_MODIFIER, $_token, - 1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE); 39 } 40 } 41 42 foreach ($_tokens as $token) { 43 $_space = !!preg_match('!^\s$!S' . Smarty::$_UTF8_MODIFIER, $token); 44 $token_length = mb_strlen($token, Smarty::$_CHARSET); 45 $length += $token_length; 46 47 if ($length > $width) { 48 // remove space before inserted break 49 if ($_previous) { 50 $t = mb_substr($t, 0, - 1, Smarty::$_CHARSET); 51 } 52 53 if (!$_space) { 54 // add the break before the token 55 if (!empty($t)) { 56 $t .= $break; 57 } 58 $length = $token_length; 59 } 60 } elseif ($token == "\n") { 61 // hard break must reset counters 62 $_previous = 0; 63 $length = 0; 64 } 65 $_previous = $_space; 66 // add the token 67 $t .= $token; 68 } 69 } 70 71 return $t; 72 } 73 }