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.
 
 
 
 
 

98 lines
1.9 KiB

  1. <?php
  2. /**
  3. * WP_MatchesMapRegex helper class
  4. *
  5. * @package WordPress
  6. * @since 4.7.0
  7. */
  8. /**
  9. * Helper class to remove the need to use eval to replace $matches[] in query strings.
  10. *
  11. * @since 2.9.0
  12. */
  13. class WP_MatchesMapRegex {
  14. /**
  15. * store for matches
  16. *
  17. * @access private
  18. * @var array
  19. */
  20. private $_matches;
  21. /**
  22. * store for mapping result
  23. *
  24. * @access public
  25. * @var string
  26. */
  27. public $output;
  28. /**
  29. * subject to perform mapping on (query string containing $matches[] references
  30. *
  31. * @access private
  32. * @var string
  33. */
  34. private $_subject;
  35. /**
  36. * regexp pattern to match $matches[] references
  37. *
  38. * @var string
  39. */
  40. public $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // magic number
  41. /**
  42. * constructor
  43. *
  44. * @param string $subject subject if regex
  45. * @param array $matches data to use in map
  46. */
  47. public function __construct($subject, $matches) {
  48. $this->_subject = $subject;
  49. $this->_matches = $matches;
  50. $this->output = $this->_map();
  51. }
  52. /**
  53. * Substitute substring matches in subject.
  54. *
  55. * static helper function to ease use
  56. *
  57. * @static
  58. * @access public
  59. *
  60. * @param string $subject subject
  61. * @param array $matches data used for substitution
  62. * @return string
  63. */
  64. public static function apply($subject, $matches) {
  65. $oSelf = new WP_MatchesMapRegex($subject, $matches);
  66. return $oSelf->output;
  67. }
  68. /**
  69. * do the actual mapping
  70. *
  71. * @access private
  72. * @return string
  73. */
  74. private function _map() {
  75. $callback = array($this, 'callback');
  76. return preg_replace_callback($this->_pattern, $callback, $this->_subject);
  77. }
  78. /**
  79. * preg_replace_callback hook
  80. *
  81. * @access public
  82. * @param array $matches preg_replace regexp matches
  83. * @return string
  84. */
  85. public function callback($matches) {
  86. $index = intval(substr($matches[0], 9, -1));
  87. return ( isset( $this->_matches[$index] ) ? urlencode($this->_matches[$index]) : '' );
  88. }
  89. }