modifier.regex_replace.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /**
  3. * Smarty plugin
  4. *
  5. * @package Smarty
  6. * @subpackage PluginsModifier
  7. */
  8. /**
  9. * Smarty regex_replace modifier plugin
  10. *
  11. * Type: modifier<br>
  12. * Name: regex_replace<br>
  13. * Purpose: regular expression search/replace
  14. *
  15. * @link http://smarty.php.net/manual/en/language.modifier.regex.replace.php
  16. * regex_replace (Smarty online manual)
  17. * @author Monte Ohrt <monte at ohrt dot com>
  18. * @param string $string input string
  19. * @param string|array $search regular expression(s) to search for
  20. * @param string|array $replace string(s) that should be replaced
  21. * @return string
  22. */
  23. function smarty_modifier_regex_replace($string, $search, $replace)
  24. {
  25. if(is_array($search)) {
  26. foreach($search as $idx => $s) {
  27. $search[$idx] = _smarty_regex_replace_check($s);
  28. }
  29. } else {
  30. $search = _smarty_regex_replace_check($search);
  31. }
  32. return preg_replace($search, $replace, $string);
  33. }
  34. /**
  35. * @param string $search string(s) that should be replaced
  36. * @return string
  37. * @ignore
  38. */
  39. function _smarty_regex_replace_check($search)
  40. {
  41. // null-byte injection detection
  42. // anything behind the first null-byte is ignored
  43. if (($pos = strpos($search,"\0")) !== false) {
  44. $search = substr($search,0,$pos);
  45. }
  46. // remove eval-modifier from $search
  47. if (preg_match('!([a-zA-Z\s]+)$!s', $search, $match) && (strpos($match[1], 'e') !== false)) {
  48. $search = substr($search, 0, -strlen($match[1])) . preg_replace('![e\s]+!', '', $match[1]);
  49. }
  50. return $search;
  51. }
  52. ?>