shared.mb_wordwrap.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 = preg_split('!(\s)!S' . Smarty::$_UTF8_MODIFIER, $str, - 1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
  26. $length = 0;
  27. $t = '';
  28. $_previous = false;
  29. foreach ($tokens as $_token) {
  30. $token_length = mb_strlen($_token, Smarty::$_CHARSET);
  31. $_tokens = array($_token);
  32. if ($token_length > $width) {
  33. // remove last space
  34. $t = mb_substr($t, 0, - 1, Smarty::$_CHARSET);
  35. $_previous = false;
  36. $length = 0;
  37. if ($cut) {
  38. $_tokens = preg_split('!(.{' . $width . '})!S' . Smarty::$_UTF8_MODIFIER, $_token, - 1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
  39. // broken words go on a new line
  40. $t .= $break;
  41. }
  42. }
  43. foreach ($_tokens as $token) {
  44. $_space = !!preg_match('!^\s$!S' . Smarty::$_UTF8_MODIFIER, $token);
  45. $token_length = mb_strlen($token, Smarty::$_CHARSET);
  46. $length += $token_length;
  47. if ($length > $width) {
  48. // remove space before inserted break
  49. if ($_previous && $token_length < $width) {
  50. $t = mb_substr($t, 0, - 1, Smarty::$_CHARSET);
  51. }
  52. // add the break before the token
  53. $t .= $break;
  54. $length = $token_length;
  55. // skip space after inserting a break
  56. if ($_space) {
  57. $length = 0;
  58. continue;
  59. }
  60. } elseif ($token == "\n") {
  61. // hard break must reset counters
  62. $_previous = 0;
  63. $length = 0;
  64. } else {
  65. // remember if we had a space or not
  66. $_previous = $_space;
  67. }
  68. // add the token
  69. $t .= $token;
  70. }
  71. }
  72. return $t;
  73. }
  74. }