Test if a regular expression is a valid one in PHP

前端 未结 6 1924
太阳男子
太阳男子 2020-12-16 14:24

I am writing a form validation class and wish to include regular expressions in the validation. Therefore, the regex provided isn\'t guaranteed to be valid.

How can

6条回答
  •  暖寄归人
    2020-12-16 15:20

    PHP has progressed quite a bit since this question was first asked (and answered). You can now (PHP 5.2+) simply write the following to, not only test if the regular expression is valid, but to get the detailed error message if it's not:

    if(@preg_match($pattern, '') === false){
       echo error_get_last()["message"];
    }
    

    Placed in a function

    /**
     * Return an error message if the given pattern argument or its underlying regular expression
     * are not syntactically valid. Otherwise (if they are valid), NULL is returned.
     *
     * @param $pattern
     *
     * @return string|null
     */
    function regexHasErrors($pattern): ?string
    {
        if(@preg_match($pattern, '') === false){
            //Silence the error by using a @
    
            return str_replace("preg_match(): ", "", error_get_last()["message"]);
            //Make it prettier by removing the function name prefix
        }
        return NULL;
    }
    

    Demo

提交回复
热议问题