Test if a regular expression is a valid one in PHP

前端 未结 6 1921
太阳男子
太阳男子 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:16

    You shouldn't be using @ to silence all errors because it also silences fatal errors.

    function isRegularExpression($string) {
      set_error_handler(function() {}, E_WARNING);
      $isRegularExpression = preg_match($string, "") !== FALSE;
      restore_error_handler();
      return isRegularExpression;
    }
    

    This only silences warnings for the preg_match call.

提交回复
热议问题