Test if a regular expression is a valid one in PHP

前端 未结 6 1929
太阳男子
太阳男子 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:05

    When you have error reporting on, you can't get away with simply testing the boolean result. If the regex fails warnings are thrown (i.e. 'Warning: No ending delimiter xxx found'.)

    What I find odd, is that the PHP documentation tells nothing about these thrown warnings.

    Below is my solution for this problem, using try, catch.

    //Enable all errors to be reported. E_WARNING is what we must catch, but I like to have all errors reported, always.
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    //My error handler for handling exceptions.
    set_error_handler(function($severity, $message, $file, $line)
    {
        if(!(error_reporting() & $severity))
        {
            return;
        }
        throw new ErrorException($message, $severity, $severity, $file, $line);
    });
    
    //Very long function name for example purpose.
    function checkRegexOkWithoutNoticesOrExceptions($test)
    {
        try
        {
            preg_match($test, '');
            return true;
        }
        catch(Exception $e)
        {
            return false;
        }
    }
    

提交回复
热议问题