How to detect if a string is a regex

5

Assuming I have the string:

$regex = "/[^a-z_\-0-9]/i";

Is there anything native to php to test if it's a valid regex?

If not, what would be the best way to test this?

    
asked by anonymous 01.03.2018 / 22:31

1 answer

6

The preg_match will return a value type int will be valid, if regex is valid but not "match the string" will return zero ( 0 ).

Now if the regex is invalid the preg_match will return a boolean value instead of int , which will be false

So for example, this is a valid regex with a value (string) that "home" will return int(1) because it has been married and the regex is valid:

var_dump(preg_match('#^[a-z]+$#', 'abcdef'));

Now this will return int(0) , regex is valid:

var_dump(preg_match('#^[a-z]+$#', '100000'));

Now an invalid regex will return bool(false) :

var_dump(preg_match('#^[a-z#', '100000'));

But it's important to note that it emits a warning , something like:

PHP Warning:  preg_match(): Compilation failed: missing terminating ] for character class at offset 5

But a warning is not necessarily an error, it would be more for a warning, on production servers this type of message is usually turned off ( display_errors=off ), still appear in the log file, but does not affect script execution, which will run normally until the end.

If you really want to do a specific test, maybe you are creating a regex collection, for example you are creating a system that the person registers with the custom validators themselves, so you can create a test like this:

/**
 * @param string $regex
 * @return bool
 */
function validate_regex($regex)
{
     return preg_match($regex, '') !== false;
}

And the usage looks like this:

validate_regex('/[^a-z_\-0-9]/i'); //Retorna TRUE
validate_regex('/[^a-z_\-0-9/i'); //Retorna FALSE
    
01.03.2018 / 22:38