modifier.truncate.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 lenght 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 = '...',
  27. $break_words = false, $middle = false)
  28. {
  29. if ($length == 0)
  30. return '';
  31. if (is_callable('mb_strlen')) {
  32. if (mb_detect_encoding($string, 'UTF-8, ISO-8859-1') === 'UTF-8') {
  33. // $string has utf-8 encoding
  34. if (mb_strlen($string) > $length) {
  35. $length -= min($length, mb_strlen($etc));
  36. if (!$break_words && !$middle) {
  37. $string = preg_replace('/\s+?(\S+)?$/u', '', mb_substr($string, 0, $length + 1));
  38. }
  39. if (!$middle) {
  40. return mb_substr($string, 0, $length) . $etc;
  41. } else {
  42. return mb_substr($string, 0, $length / 2) . $etc . mb_substr($string, - $length / 2);
  43. }
  44. } else {
  45. return $string;
  46. }
  47. }
  48. }
  49. // $string has no utf-8 encoding
  50. if (strlen($string) > $length) {
  51. $length -= min($length, strlen($etc));
  52. if (!$break_words && !$middle) {
  53. $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
  54. }
  55. if (!$middle) {
  56. return substr($string, 0, $length) . $etc;
  57. } else {
  58. return substr($string, 0, $length / 2) . $etc . substr($string, - $length / 2);
  59. }
  60. } else {
  61. return $string;
  62. }
  63. }
  64. ?>