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.

shared.mb_wordwrap.php 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. $_space = false;
  30. foreach ($tokens as $_token) {
  31. $token_length = mb_strlen($_token, Smarty::$_CHARSET);
  32. $_tokens = array($_token);
  33. if ($token_length > $width) {
  34. if ($cut) {
  35. $_tokens = preg_split('!(.{' . $width . '})!S' . Smarty::$_UTF8_MODIFIER, $_token, - 1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
  36. }
  37. }
  38. foreach ($_tokens as $token) {
  39. $_space = !!preg_match('!^\s$!S' . Smarty::$_UTF8_MODIFIER, $token);
  40. $token_length = mb_strlen($token, Smarty::$_CHARSET);
  41. $length += $token_length;
  42. if ($length > $width) {
  43. // remove space before inserted break
  44. if ($_previous) {
  45. $t = mb_substr($t, 0, - 1, Smarty::$_CHARSET);
  46. }
  47. if (!$_space) {
  48. // add the break before the token
  49. if (!empty($t)) {
  50. $t .= $break;
  51. }
  52. $length = $token_length;
  53. }
  54. } elseif ($token == "\n") {
  55. // hard break must reset counters
  56. $_previous = 0;
  57. $length = 0;
  58. }
  59. $_previous = $_space;
  60. // add the token
  61. $t .= $token;
  62. }
  63. }
  64. return $t;
  65. }
  66. }