class-wp-matchesmapregex.php 1.8 KB

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