modifier.truncate.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /**
  3. * Smarty plugin
  4. *
  5. * @package Smarty
  6. * @subpackage PluginsModifier
  7. */
  8. /**
  9. * Smarty truncate modifier plugin
  10. *
  11. * Type: modifier<br>
  12. * Name: truncate<br>
  13. * Purpose: Truncate a string to a certain length if necessary,
  14. * optionally splitting in the middle of a word, and
  15. * appending the $etc string or inserting $etc into the middle.
  16. *
  17. * @link http://smarty.php.net/manual/en/language.modifier.truncate.php truncate (Smarty online manual)
  18. * @author Monte Ohrt <monte at ohrt dot com>
  19. * @param string $string input string
  20. * @param integer $length length of truncated text
  21. * @param string $etc end string
  22. * @param boolean $break_words truncate at word boundary
  23. * @param boolean $middle truncate in the middle of text
  24. * @return string truncated string
  25. */
  26. function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false) {
  27. if ($length == 0)
  28. return '';
  29. if (SMARTY_MBSTRING /* ^phpunit */&&empty($_SERVER['SMARTY_PHPUNIT_DISABLE_MBSTRING'])/* phpunit$ */) {
  30. if (mb_strlen($string, SMARTY_RESOURCE_CHAR_SET) > $length) {
  31. $length -= min($length, mb_strlen($etc, SMARTY_RESOURCE_CHAR_SET));
  32. if (!$break_words && !$middle) {
  33. $string = preg_replace('/\s+?(\S+)?$/u', '', mb_substr($string, 0, $length + 1, SMARTY_RESOURCE_CHAR_SET));
  34. }
  35. if (!$middle) {
  36. return mb_substr($string, 0, $length, SMARTY_RESOURCE_CHAR_SET) . $etc;
  37. }
  38. return mb_substr($string, 0, $length / 2, SMARTY_RESOURCE_CHAR_SET) . $etc . mb_substr($string, - $length / 2, $length, SMARTY_RESOURCE_CHAR_SET);
  39. }
  40. return $string;
  41. }
  42. // no MBString fallback
  43. if (isset($string[$length])) {
  44. $length -= min($length, strlen($etc));
  45. if (!$break_words && !$middle) {
  46. $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
  47. }
  48. if (!$middle) {
  49. return substr($string, 0, $length) . $etc;
  50. }
  51. return substr($string, 0, $length / 2) . $etc . substr($string, - $length / 2);
  52. }
  53. return $string;
  54. }
  55. ?>