How to detect if a string is a regex

Asked

Viewed 138 times

5

Supposing I have the string:

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

There is something native to php to test if it is a regex validate?

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

  • Native would be trying to compile the regex and check the error. Now, not native... you cannot validate a regex using regex... You’d have to build a context-free grammar for that

1 answer

6


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

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

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

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

Now you will return int(0), the 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 is important to note that it issues 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 do not affect the execution of the script, which will run normally until the end.

If you really want to do a specific test, if you are creating a collection of regex, for example you are creating a system that people register their own custom validators, then you can create a test like this:

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

And the use goes like this:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.