-1

I have already tried to include - in code but I always have problem

What is the correct way to include this character "-" in

!preg_match("/^[a-zA-Z0-9\. ]*$/", $home)

Thanks

Toni Mhb
  • 53
  • 6
  • You need to escape it (`\-`), or make it the first charater inside `[]`. – user229044 Jul 19 '14 at 17:09
  • @meagar: C#?? there are some differences in the regex syntax supported by different languages (even though in this case it is the same), so I think you shouldn't do that. – Karoly Horvath Jul 19 '14 at 17:15
  • @meagar: i know of no regex dialects that would have a syntax for escaping you describe. `[a\-z]` matches all lowercase characters. – just somebody Jul 19 '14 at 17:54
  • @justsomebody `[-a-z]` and `[a-z-]` both match `-` and `a-z`. You don't have to escape it unless it's ambiguous. – user229044 Jul 20 '14 at 16:11
  • @meagar yes, you can make it stand for itself inside a character class if you put it first or last. but there's no amount of backslashes you could put in front of the dash to make it non-special if it's not at those positions. *You need to escape it (\-)* is wrong. – just somebody Jul 20 '14 at 21:31
  • @justsomebody I'm sorry but you're demonstrably wrong. The correct amount of backslash is to make it "non-special" is 1. `[a\-z]` matches only three characters, `'a'`, a literal `'-'`, or `'z'`. It is not equivalent to `[a-z]`, it's equivalent to `[-az]` or `[az-]`. Your claim, "`[a\-z]` matches all lower case characters", is wrong, at least in PHP and JavaScript's "regex dialects", and ever other dialect *I've* heard of. Just look at the answers posted below, and the answers posted in the linked duplicate, and virtually any other of the dozens of duplicate questions. – user229044 Jul 20 '14 at 22:16
  • @meagar you are correct. i don't know when this capability appeared but it's even in perl-5.20.0. sorry about spreading BS. :( – just somebody Jul 21 '14 at 11:49

2 Answers2

0

Inside character classes, - signs need to be escaped like this:

!preg_match("/^[a-zA-Z0-9\. \-]*$/", $home);

Also, you can drop A-Z from the character class and add the i flag to the regex like this:

!preg_match("/^[a-z0-9\. \-]*$/i", $home);
just somebody
  • 18,602
  • 6
  • 51
  • 60
Jonan
  • 2,485
  • 3
  • 24
  • 42
0

From the manual:

If a minus character is required in a class, it must be escaped with a backslash or appear in a position where it cannot be interpreted as indicating a range, typically as the first or last character in the class.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176