Test if a regular expression is a valid one in PHP

前端 未结 6 1925
太阳男子
太阳男子 2020-12-16 14:24

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

6条回答
  •  暖寄归人
    2020-12-16 15:14

    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
    }
    

提交回复
热议问题