From 82122089f90a7618eeb86f87a1af948b3c361eb6 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Tue, 20 Feb 2024 13:48:58 +0100 Subject: [PATCH] Check: add regex() --- src/Check.php | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/Check.php b/src/Check.php index 113a6e8..92fc3cc 100644 --- a/src/Check.php +++ b/src/Check.php @@ -134,6 +134,31 @@ class Check { 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