| 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 = $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 |
/** |
| 28 |
* Regex replace the current pattern with $replace_pattern, applied to $target |
| 29 |
* |
| 30 |
* Note: if the pattern is invalid it will return $target |
| 31 |
* |
| 32 |
* @param string $replace_pattern The regex replace pattern |
| 33 |
* @param string $target Text to match the regex against |
| 34 |
* @return string Replaced text |
| 35 |
*/ |
| 36 |
public function replace( $replace_pattern, $target ) { |
| 37 |
$result = @preg_replace( $this->get_regex(), $replace_pattern, $target ); |
| 38 |
return is_null( $result ) ? $target : $result; |
| 39 |
} |
| 40 |
|
| 41 |
private function get_regex() { |
| 42 |
$at_escaped = str_replace( '@', '\\@', $this->pattern ); |
| 43 |
$case = ''; |
| 44 |
|
| 45 |
if ( $this->is_ignore_case() ) { |
| 46 |
$case = 'i'; |
| 47 |
} |
| 48 |
|
| 49 |
return '@' . $at_escaped . '@' . $case; |
| 50 |
} |
| 51 |
|
| 52 |
public function is_ignore_case() { |
| 53 |
return $this->case; |
| 54 |
} |
| 55 |
} |
| 56 |
|