modifier.highlight.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. /**
  3. * Smarty modifier to highlight a substring
  4. *
  5. * @author Christopher Han <xiphux@gmail.com>
  6. * @copyright Copyright (c) 2010 Christopher Han
  7. * @package GitPHP
  8. * @subpackage Smarty
  9. *
  10. * @param string $haystack string to search in
  11. * @param string $needle substring to search for
  12. * @param int $trimlen length to trim string to
  13. * @param bool $escape true to html escape the string
  14. * @param string $highlightclass CSS class to highlight with
  15. * @return string highlighted string
  16. */
  17. function smarty_modifier_highlight($haystack, $needle, $trimlen = NULL, $escape = false, $highlightclass = 'searchmatch')
  18. {
  19. if (preg_match("/(.*)(" . quotemeta($needle) . ")(.*)/i",$haystack,$regs)) {
  20. if (isset($trimlen) && ($trimlen > 0)) {
  21. $linelen = strlen($regs[0]);
  22. if ($linelen > $trimlen) {
  23. $matchlen = strlen($regs[2]);
  24. $remain = floor(($trimlen - $matchlen) / 2);
  25. $leftlen = strlen($regs[1]);
  26. $rightlen = strlen($regs[3]);
  27. if ($leftlen > $remain) {
  28. $leftremain = $remain;
  29. if ($rightlen < $remain)
  30. $leftremain += ($remain - $rightlen);
  31. $regs[1] = "…" . substr($regs[1], ($leftlen - ($leftremain - 3)));
  32. }
  33. if ($rightlen > $remain) {
  34. $rightremain = $remain;
  35. if ($leftlen < $remain)
  36. $rightremain += ($remain - $leftlen);
  37. $regs[3] = substr($regs[3],0,$rightremain-3) . "…";
  38. }
  39. }
  40. }
  41. if ($escape) {
  42. $regs[1] = htmlspecialchars($regs[1]);
  43. $regs[2] = htmlspecialchars($regs[2]);
  44. $regs[3] = htmlspecialchars($regs[3]);
  45. }
  46. $ret = $regs[1] . "<span";
  47. if ($highlightclass)
  48. $ret .= " class=\"" . $highlightclass . "\"";
  49. $ret .= ">" . $regs[2] . "</span>" . $regs[3];
  50. return $ret;
  51. }
  52. return $haystack;
  53. }
  54. ?>