preg_match compilation failed: invalid range in character class [duplicate]

别来无恙 提交于 2019-12-12 13:50:47

问题


I'm using Laravel as my framework and I'm trying to use my own preg_match function in order to validate a form.

Below is my code:

Validator::extend('alpha_num_spaces', function ($attribute, $value)
{
    return preg_match('/^([-a-z0-9_-\s])+$/i', $value);
});

Now, I've run this on the production server and it works fine, however, on my local machine I receive:

preg_match(): Compilation failed: invalid range in character class at offset 13

My guess is something to do with the difference in PHP versions? But I'm basing that purely on a guess. Or perhaps there is something in fact wrong with the regex?

Thanks in advance.


回答1:


You need to use:

preg_match('/^([-a-z0-9_\s])+$/i', $value);

OR

preg_match('/^([-\w\s])+$/i', $value);

You have an unescaped hyphen in the middle of your character class.

Hyphen needs to be at first or last place in character class Or it should be escaped. Besides you already have a hyphen at first place so no need to have it again.




回答2:


"My guess is something to do with the difference in PHP versions". Indeed, I think that the version of your production server see \s as a literal s and ignore the backslash. (to be sure, test a string with a space). But your test server see a range between a character and a shorthand character class, that has obviously no sense.

Recent versions of PCRE are smart enough (when it is unambigous) to see that an hyphen do not define a character range when it is preceded by a shorthand character class or a range. For example: [\s-ABC] or [0-9-ABC] are correct.(in these cases you don't need to escape it)

Conclusion, you can write:

[-a-z0-9_\s]
[a-z0-9_\s-]
[a-z0-9-_\s]
[a-z-0-9_\s]
[a-z0-9\s-_]
[a-z0-9_\-\s]

but not:

[a-z0-9_-\s]



回答3:


The hyphen must be the last character, if you want it to be one of the matching characters:

return preg_match('/^([-a-z0-9_\s-])+$/i', $value);


来源:https://stackoverflow.com/questions/27426645/preg-match-compilation-failed-invalid-range-in-character-class

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