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.truncate.php 2.1KB

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