You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

modifier.mb_wordwrap.php 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * Smarty plugin
  4. *
  5. * @package Smarty
  6. * @subpackage PluginsModifier
  7. */
  8. /**
  9. * Smarty wordwrap modifier plugin
  10. * Type: modifier
  11. * Name: mb_wordwrap
  12. * Purpose: 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_modifier_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. foreach ($tokens as $_token) {
  33. $token_length = mb_strlen($_token, Smarty::$_CHARSET);
  34. $_tokens = array($_token);
  35. if ($token_length > $width) {
  36. if ($cut) {
  37. $_tokens = preg_split('!(.{' . $width . '})!S' . Smarty::$_UTF8_MODIFIER,
  38. $_token,
  39. -1,
  40. PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
  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) {
  50. $t = mb_substr($t, 0, -1, Smarty::$_CHARSET);
  51. }
  52. if (!$_space) {
  53. // add the break before the token
  54. if (!empty($t)) {
  55. $t .= $break;
  56. }
  57. $length = $token_length;
  58. }
  59. } else if ($token === "\n") {
  60. // hard break must reset counters
  61. $length = 0;
  62. }
  63. $_previous = $_space;
  64. // add the token
  65. $t .= $token;
  66. }
  67. }
  68. return $t;
  69. }