PluginProbe
Redirection / 5.3.7
Redirection v5.3.7
5.10.0 5.9.0 5.8.1 5.8.0 3.7.2 3.7.3 4.0 4.0.1 4.1 4.1.1 4.2 4.2.1 4.2.2 4.2.3 4.3 4.3.1 4.3.2 4.3.3 4.4 4.4.1 4.4.2 4.5 4.5.1 4.6.2 4.7.1 All 130 releases
redirection / models / regex.php

regex.php in Redirection 5.3.7, at models/regex.php

78 lines 1.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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