开发者

Improve this regex to support spaces

I want to make this regex to support white spaces too but ( not talking about \n \r ).

preg_match('/^[a-zA-Z0-9_-]+$/', $text);

when i tr开发者_Go百科y to do :

preg_match('/^[a-zA-Z0-9_- ]+$/', $text);

It returns: Compilation failed: range out of order in character class at offset 13

Recaping everything, it should only match a-z & A-Z & 0-9 & - & _ & space

Thanks


use

preg_match('/^[a-zA-Z0-9_ -]+$/', $text);

otherwise ([_- ]) will be understood as range


It's because you have a - before the space which forms a range _-, which is illegal since a space is lexicographically less than _. To solve the problem, move the - after the space, so you no longer form a range from the -.

preg_match('/^[a-zA-Z0-9_ -]+$/', $text);

Also consider using \s to match any whitespace character, including space, tab, newline and cariage returns.

preg_match('/^[a-zA-Z0-9_\s-]+$/', $text);

PS: Be glad you didn't have a legal range, that would've been a nasty bug to identify. :)


The _-  in [a-zA-Z0-9_- ] is interpreted as character range from _ (LOW LINE, 0x5F) to   (SPACE, 0x20). But since _ comes after  , the character range _-  is invalid.

Since you don’t want that character range, you either need to escape the - so that it’s not interpreted as character range:

[a-zA-Z0-9_\- ]

Or rearrange the character so that the - will not be interpreted as character range indicator like when putting it just after another character range or right at the begin or the end of the character class:

[a-z-A-Z0-9_ ]
[a-zA-Z-0-9_ ]
[a-zA-Z0-9-_ ]
[-a-zA-Z0-9_ ]
[a-zA-Z0-9_ -]


You need to escape the last hyphen:

preg_match('/^[a-zA-Z0-9_\- ]+$/', $text);


Use \S for whitespace

Documentation is found here


I believe that your regexp string is evaluating the underscore dash space "_- " as a range. Try escaping the dash.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜