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