Laravel preg_match(): Unknown modifier ']'

一个人想着一个人 提交于 2020-02-23 03:56:10

问题


Im wokring on Laravel 4.2. Im trying to use validator to validate a name field with regex here is my rule below:

public static $rules_save = [
    'name'      => 'required|regex:/[XI0-9/]+/|unique:classes'
];

But as soon as I call the rule to be validated an error is thrown see below:

preg_match(): Unknown modifier ']'

In the following location:

protected function validateRegex($attribute, $value, $parameters)
    {
        $this->requireParameterCount(1, $parameters, 'regex');

        return preg_match($parameters[0], $value); // **ON THIS LINE**
    }

回答1:


Since you need to include a / into the character class, you need to either esacpe it:

'name'      => 'required|regex:/[XI0-9\/]+/|unique:classes'
                                      ^

Or use other regex delimiters.

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

Often used delimiters are forward slashes (/), hash signs (#) and tildes (~).




回答2:


As the first poster(stribizhev) pointed out, you need to escape the forward slash /, and this is because the backslash / is used as a delimiter in that pattern. Therefore, making it to act like a special character within the character class.

Therefore your pattern should be like this

/[XI0-9\/]+/

But if you make use of other delimiters e.g #, then there would be no need to escape the forward slash.

#[XI0-9/]+#

here, i didn't escape the forward slash because i used # as a delimiter

Hope this helps.

For more info, check out the link posted by stribizhev.



来源:https://stackoverflow.com/questions/32807517/laravel-preg-match-unknown-modifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!