Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a regular expression is a valid one in PHP

Tags:

regex

php

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 I (efficiently) check that the regex is valid?

like image 606
CrazeD Avatar asked Jan 11 '12 18:01

CrazeD


People also ask

Is there a regular expression to detect a valid regular expression?

No, if you are strictly speaking about regular expressions and not including some regular expression implementations that are actually context free grammars. There is one limitation of regular expressions which makes it impossible to write a regex that matches all and only regexes.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What does $1 do in regex?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.


2 Answers

Use the pattern in your preg_* calls. If the function returns false there is likely a problem with your pattern. As far as I know this is the easiest way to check if a regex pattern is valid in PHP.


Here's an example specifying the right kind of boolean check:

$invalidPattern = 'i am not valid regex';
$subject = 'This is some text I am searching in';
if (@preg_match($invalidPattern, $subject) === false) {
    // the regex failed and is likely invalid
}
like image 106
Charles Sprayberry Avatar answered Sep 17 '22 14:09

Charles Sprayberry


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;
    }
}
like image 30
twicejr Avatar answered Sep 19 '22 14:09

twicejr