Check: add regex()

This commit is contained in:
Benjamin Renard 2024-02-20 13:48:58 +01:00
parent 99c350267f
commit 82122089f9
Signed by: bn8
GPG key ID: 3E2E1CE1907115BC

View file

@ -134,6 +134,31 @@ class Check {
return false; return false;
} }
/**
* Check value is a valid regex (PREG)
* @param mixed $value The value to check
* @param boolean $return_error Set to true to get an error message about the error
* @return ( $return_error is true ? string|true : boolean )
*/
public static function regex($value, $return_error=false) {
if (!is_string($value))
return $return_error?'PREG ERROR: not a string':false;
if (@preg_match($value, null) === false) { // @phpstan-ignore-line
if ($return_error)
return sprintf(
'PREG ERROR #%d%s',
preg_last_error(),
(
function_exists('preg_last_error_msg')?
sprintf(" (%s)", preg_last_error_msg()):
""
)
);
return false;
}
return true;
}
} }
# vim: tabstop=2 shiftwidth=2 softtabstop=2 expandtab # vim: tabstop=2 shiftwidth=2 softtabstop=2 expandtab