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