CodeOverload
CodeOverload

Reputation: 48565

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 try 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

Upvotes: 0

Views: 225

Answers (6)

Gumbo
Gumbo

Reputation: 655795

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_ -]

Upvotes: 1

moinudin
moinudin

Reputation: 138507

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. :)

Upvotes: 1

Aaron
Aaron

Reputation: 1009

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

Upvotes: 0

Michael
Michael

Reputation: 1231

Use \S for whitespace

Documentation is found here

Upvotes: 0

PleaseStand
PleaseStand

Reputation: 32122

You need to escape the last hyphen:

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

Upvotes: 0

knittl
knittl

Reputation: 265938

use

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

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

Upvotes: 4

Related Questions