Skip to content

Instantly share code, notes, and snippets.

@lastguest
Created September 7, 2018 12:57
Show Gist options
  • Save lastguest/995241b9b76288319e9224b0961d255b to your computer and use it in GitHub Desktop.
Save lastguest/995241b9b76288319e9224b0961d255b to your computer and use it in GitHub Desktop.
[PHP] Core: RegEx
<?php
class RegEx {
protected $pattern;
public function __construct($pattern){
$this->pattern = $pattern;
}
public function test($subject, $flags = 0){
if (($res = preg_match($this->pattern, $subject, $flags)) === false){
throw new \Exception(static::lastError());
} else return (bool) $res;
}
public static function lastError(){
switch($last_error = preg_last_error()){
case PREG_NO_ERROR: return false;
case PREG_INTERNAL_ERROR: return 'There is an internal error!';
case PREG_BACKTRACK_LIMIT_ERROR: return 'Backtrack limit was exhausted!';
case PREG_RECURSION_LIMIT_ERROR: return 'Recursion limit was exhausted!';
case PREG_BAD_UTF8_ERROR: return 'Bad UTF8 error!';
case PREG_BAD_UTF8_OFFSET_ERROR: return 'Bad UTF8 offset error!';
case PREG_JIT_STACKLIMIT_ERROR: return 'JIT stack limit was exhausted!';
default: return array_flip(get_defined_constants(true)['pcre'])[$last_error];
}
}
}
class RegExMatches implements ArrayAccess {
protected $pattern,
$matches;
public function __construct($pattern, $matches){
$this->pattern = $pattern;
$this->matches = $matches;
}
public function offsetExists($offset){
return isset($this->matches[$offset]);
}
public function offsetGet($offset){
return $this->matches[$offset];
}
public function offsetSet($offset, $value){}
public function offsetUnset($offset){}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment