shared.mb_wordwrap.php 2.7 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. * @param string $str the string to wrap
  14. * @param int $width the width of the output
  15. * @param string $break the character used to break the line
  16. * @param boolean $cut ignored parameter, just for the sake of
  17. * @return string wrapped string
  18. * @author Rodney Rehm
  19. */
  20. function smarty_mb_wordwrap($str, $width=75, $break="\n", $cut=false)
  21. {
  22. // break words into tokens using white space as a delimiter
  23. $tokens = preg_split('!(\s)!uS', $str, -1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
  24. $length = 0;
  25. $t = '';
  26. $_previous = false;
  27. foreach ($tokens as $_token) {
  28. $token_length = mb_strlen($_token, SMARTY_RESOURCE_CHAR_SET);
  29. $_tokens = array($_token);
  30. if ($token_length > $width) {
  31. // remove last space
  32. $t = mb_substr($t, 0, -1, SMARTY_RESOURCE_CHAR_SET);
  33. $_previous = false;
  34. $length = 0;
  35. if ($cut) {
  36. $_tokens = preg_split('!(.{' . $width . '})!uS', $_token, -1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
  37. // broken words go on a new line
  38. $t .= $break;
  39. }
  40. }
  41. foreach ($_tokens as $token) {
  42. $_space = !!preg_match('!^\s$!uS', $token);
  43. $token_length = mb_strlen($token, SMARTY_RESOURCE_CHAR_SET);
  44. $length += $token_length;
  45. if ($length > $width) {
  46. // remove space before inserted break
  47. if ($_previous && $token_length < $width) {
  48. $t = mb_substr($t, 0, -1, SMARTY_RESOURCE_CHAR_SET);
  49. }
  50. // add the break before the token
  51. $t .= $break;
  52. $length = $token_length;
  53. // skip space after inserting a break
  54. if ($_space) {
  55. $length = 0;
  56. continue;
  57. }
  58. } else if ($token == "\n") {
  59. // hard break must reset counters
  60. $_previous = 0;
  61. $length = 0;
  62. } else {
  63. // remember if we had a space or not
  64. $_previous = $_space;
  65. }
  66. // add the token
  67. $t .= $token;
  68. }
  69. }
  70. return $t;
  71. }
  72. }
  73. ?>