class-wp-matchesmapregex.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. * @param string $subject subject
  55. * @param array $matches data used for substitution
  56. * @return string
  57. */
  58. public static function apply( $subject, $matches ) {
  59. $oSelf = new WP_MatchesMapRegex( $subject, $matches );
  60. return $oSelf->output;
  61. }
  62. /**
  63. * do the actual mapping
  64. *
  65. * @return string
  66. */
  67. private function _map() {
  68. $callback = array( $this, 'callback' );
  69. return preg_replace_callback( $this->_pattern, $callback, $this->_subject );
  70. }
  71. /**
  72. * preg_replace_callback hook
  73. *
  74. * @param array $matches preg_replace regexp matches
  75. * @return string
  76. */
  77. public function callback( $matches ) {
  78. $index = intval( substr( $matches[0], 9, -1 ) );
  79. return ( isset( $this->_matches[ $index ] ) ? urlencode( $this->_matches[ $index ] ) : '' );
  80. }
  81. }