class-wp-matchesmapregex.php 1.8 KB

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