| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Regular expression helper |
| 5 |
*/ |
| 6 |
class Red_Regex { |
| 7 |
private $pattern; |
| 8 |
private $case; |
| 9 |
|
| 10 |
public function __construct( $pattern, $case_insensitive = false ) { |
| 11 |
$this->pattern = rawurldecode( $pattern ); |
| 12 |
$this->case = $case_insensitive; |
| 13 |
} |
| 14 |
|
| 15 |
/** |
| 16 |
* Does $target match the regex pattern, applying case insensitivity if set. |
| 17 |
* |
| 18 |
* Note: if the pattern is invalid it will not match |
| 19 |
* |
| 20 |
* @param string $target Text to match the regex against |
| 21 |
* @return boolean match |
| 22 |
*/ |
| 23 |
public function is_match( $target ) { |
| 24 |
return @preg_match( $this->get_regex(), $target, $matches ) > 0; |
| 25 |
} |
| 26 |
|
| 27 |
private function encode_path( $path ) { |
| 28 |
return str_replace( ' ', '%20', $path ); |
| 29 |
} |
| 30 |
|
| 31 |
private function encode_query( $path ) { |
| 32 |
return str_replace( ' ', '+', $path ); |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Regex replace the current pattern with $replace_pattern, applied to $target |
| 37 |
* |
| 38 |
* Note: if the pattern is invalid it will return $target |
| 39 |
* |
| 40 |
* @param string $replace_pattern The regex replace pattern |
| 41 |
* @param string $target Text to match the regex against |
| 42 |
* @return string Replaced text |
| 43 |
*/ |
| 44 |
public function replace( $replace_pattern, $target ) { |
| 45 |
$regex = $this->get_regex(); |
| 46 |
$result = @preg_replace( $regex, $replace_pattern, $target ); |
| 47 |
|
| 48 |
if ( is_null( $result ) ) { |
| 49 |
return $target; |
| 50 |
} |
| 51 |
|
| 52 |
// Space encode the target |
| 53 |
$split = explode( '?', $result ); |
| 54 |
if ( count( $split ) === 2 ) { |
| 55 |
$result = implode( '?', [ $this->encode_path( $split[0] ), $this->encode_query( $split[1] ) ] ); |
| 56 |
} else { |
| 57 |
$result = $this->encode_path( $result ); |
| 58 |
} |
| 59 |
|
| 60 |
return $result; |
| 61 |
} |
| 62 |
|
| 63 |
private function get_regex() { |
| 64 |
$at_escaped = str_replace( '@', '\\@', $this->pattern ); |
| 65 |
$case = ''; |
| 66 |
|
| 67 |
if ( $this->is_ignore_case() ) { |
| 68 |
$case = 'i'; |
| 69 |
} |
| 70 |
|
| 71 |
return '@' . $at_escaped . '@s' . $case; |
| 72 |
} |
| 73 |
|
| 74 |
public function is_ignore_case() { |
| 75 |
return $this->case; |
| 76 |
} |
| 77 |
} |
| 78 |
|