shared.mb_wordwrap.php 2.5 KB

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