How can I check the regex?

I would like to check the correctness of the regular expression in PHP, preferably before using it. The only way to do this is actually trying preg_match() and see if it returns FALSE ?

Is there an easier / correct way to check for the correct regular expression?

+63
php regex
Dec 14 '10 at 15:17
source share
11 answers
 // This is valid, both opening ( and closing ) var_dump(preg_match('~Valid(Regular)Expression~', null) === false); // This is invalid, no opening ( for the closing ) var_dump(preg_match('~InvalidRegular)Expression~', null) === false); 

As the pozs user said , also consider placing @ before preg_match () ( @preg_match() ) in a test environment to prevent warnings or notifications.

To verify that RegExp runs it only with null (you don't need to know the data you want to test against upfront). If it returns an explicit false ( === false ), it is aborted. Otherwise, it is valid, although it does not need anything.

Therefore, there is no need to write your own RegExp validator. Wasting time ...

+124
Oct 17 '12 at 18:44
source share

I created a simple function that can be called to test preg

 function is_preg_error() { $errors = array( PREG_NO_ERROR => 'Code 0 : No errors', PREG_INTERNAL_ERROR => 'Code 1 : There was an internal PCRE error', PREG_BACKTRACK_LIMIT_ERROR => 'Code 2 : Backtrack limit was exhausted', PREG_RECURSION_LIMIT_ERROR => 'Code 3 : Recursion limit was exhausted', PREG_BAD_UTF8_ERROR => 'Code 4 : The offset didn\'t correspond to the begin of a valid UTF-8 code point', PREG_BAD_UTF8_OFFSET_ERROR => 'Code 5 : Malformed UTF-8 data', ); return $errors[preg_last_error()]; } 

You can call this function using the following code:

 preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar'); echo is_preg_error(); 



Alternative - Online Regular Expression Tester

+22
Oct 17
source share

If you want to dynamically test the regular expression preg_match(...) === false , it seems your only option. PHP has no mechanism for compiling regular expressions before using them.

You can also find preg_last_error a useful function.

On the other hand, if you have a regular expression and just want to know if it is valid before using it, there are many tools available there. I found rubular.com to be enjoyable to use.

+15
Dec 14 '10 at 15:25
source share

You can check if this is a syntactically correct regular expression with this regular expression nightmare if your engine supports recursion (PHP should).

You cannot, however algorithmically say, whether it will produce the desired results without running it.

From: Is there a regular expression to determine the correct regular expression?

 /^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/ 
+6
Oct 23
source share

Without performing a regular expression, you cannot be sure that it is valid. I recently implemented a similar RegexValidator for the Zend Framework. Works fine.

 <?php class Nuke_Validate_RegEx extends Zend_Validate_Abstract { /** * Error constant */ const ERROR_INVALID_REGEX = 'invalidRegex'; /** * Error messages * @var array */ protected $_messageTemplates = array( self::ERROR_INVALID_REGEX => "This is a regular expression PHP cannot parse."); /** * Runs the actual validation * @param string $pattern The regular expression we are testing * @return bool */ public function isValid($pattern) { if (@preg_match($pattern, "Lorem ipsum") === false) { $this->_error(self::ERROR_INVALID_REGEX); return false; } return true; } } 
+2
Oct 18 '12 at 13:21
source share

You can check the correct expression with a regular expression and up to a certain limit. Check out this stack overflow answer for more info.

Note: "recursive regular expression" is not a regular expression, and this extended version of the regular expression does not match extended regular expressions.

Better use preg_match and match with NULL as @Claudrian said

+1
Oct 19 '12 at 8:01
source share

So, for anyone who comes up with this question, you can test regular expressions in PHP using such a function.

preg_match () returns 1 if the pattern matches the given object, 0 if it is not, or FALSE if an error occurs. - PHP manual

 /** * Return an error message if the regular expression is invalid * * @param string $regex string to validate * @return string */ function invalidRegex($regex) { if(preg_match($regex, null) !== false) { return ''; } $errors = array( PREG_NO_ERROR => 'Code 0 : No errors', PREG_INTERNAL_ERROR => 'Code 1 : There was an internal PCRE error', PREG_BACKTRACK_LIMIT_ERROR => 'Code 2 : Backtrack limit was exhausted', PREG_RECURSION_LIMIT_ERROR => 'Code 3 : Recursion limit was exhausted', PREG_BAD_UTF8_ERROR => 'Code 4 : The offset didn\'t correspond to the begin of a valid UTF-8 code point', PREG_BAD_UTF8_OFFSET_ERROR => 'Code 5 : Malformed UTF-8 data', ); return $errors[preg_last_error()]; } 

What can be used like this.

 if($error = invalidRegex('/foo//')) { die($error); } 
+1
Oct 22 '12 at 19:20
source share

I'm not sure if it supports PCRE, but there is a Chrome extension in https://chrome.google.com/webstore/detail/cmmblmkfaijaadfjapjddbeaoffeccib called RegExp Tester . I haven't used it yet, but I can't vouch for it, but maybe it can be useful?

+1
Oct 23
source share

I would be inclined to tweak some unit tests for your regular expression. This way you can not only make sure that the regular expression is really valid, but also effective in matching.

I find that using TDD is an effective way to develop a regular expression and means that expanding it in the future is simplified since you already have all the available test cases.

The answer to this question gives an excellent answer to setting up unit tests.

0
Oct 19 '12 at 9:08
source share

You should try to match the regex with NULL .

In PHP> = 5.5, you can use the following to automatically receive a built-in error message, without having to define your own function to receive it:

 preg_match($regex, NULL); echo array_flip(get_defined_constants(true)['pcre'])[preg_last_error()]; 
0
Apr 01 '19 at 22:18
source share

According to the PCRE link , there is no such way to check the validity of the expression, before which it used, But I think that if someone uses an invalid expression, this is a design error in this application and not at run time, so you should be in okay.

-3
Oct 20 '12 at 12:11
source share



All Articles