How to check regex using PHP

I want to be able to check the user-entered regular expression to see if it is valid or not. The first thing I found with PHP was filter_var with the constant FILTER_VALIDATE_REGEXP , but that does not do what I want, since it should pass regex options, but I am not regex'ing against anything, so basically it's just checking the regular expression is correct.

But you understand how I can verify the correctness of the user-entered regular expression (which does not match anything).

An example of checking simple words:

 $user_inputted_regex = $_POST['regex']; // eg /([az]+)\..*([0-9]{2})/i if(is_valid_regex($user_inputted_regex)) { // The regex was valid } else { // The regex was invalid } 

Verification Examples:

 /[[0-9]/i // invalid //(.*)/ // invalid /(.*)-(.*)-(.*)/ // valid /([az]+)-([0-9_]+)/i // valid 
+6
source share
2 answers

Here's an idea ( demo ):

 function is_valid_regex($pattern) { return is_int(@preg_match($pattern, '')); } 

preg_match () returns the number of pattern matches. It will be either 0 times (no matches) or 1 time, because preg_match () will stop searching after the first match.

preg_match () returns FALSE if an error occurs.

And to get the reason why the template is not valid, use preg_last_error .

+5
source

You will need to write your own function to test the regular expression. You can check it to tell if it contains illegal characters or bad shape, but there is no way to check that it is a working expression. To do this, you will need to create a solution.

But then you realize that there really is no such thing as an invalid regular expression. The regex is based on performance. It either matches or doesn't match, and it depends on the subject of the test - even if the expression or its results seem meaningless.

In other words, you can only test a regular expression for valid syntax ... and that could be almost anything!

+2
source

Source: https://habr.com/ru/post/912630/


All Articles