1

I'm still a newbie for regular expressions. I want to create a regular expression with this rule:

if (preg_match('^[ A-Za-z0-9_-#]^', $text) == 1) {
    return true;
}
else {
    return false;
}

In short, I would like $text to accept texts, numbers, spaces, underscores, dashes, and hashes (#). Is the above reg expression correct? it always return true.

Henry Gunawan
  • 922
  • 3
  • 18
  • 38

2 Answers2

7

First off, you shouldn't use ^ as the expression boundaries, because they're also used for expression anchors; use /, ~ or # instead.

Second, the dash in the character set should be at the last position; otherwise it matches the range from _ until #, and that's probably not what you want.

Third, the expression now only matches a single character; you will want to use a multiplier such as + or *.

Lastly, you should anchor the expression so that only those valid characters are present in the string:

/^[ \w#-]+$/

Btw, I've replaced A-Za-z0-9_ with \w as a shortcut.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
2

That you can do:

  1. \w stand for [a-zA-Z0-9_]
  2. the character - have a special meaning in a character class since it is used to define ranges, thus you must place it at the begining or at the end of the class
  3. the preg_match function return 0 if there is no match or false when an error occurs, thus you don't need to test if it is equal to 1 (you can use that preg_match returns to do things)

example:

if (preg_match('~[\w #-]++~', $subject))
     ...
else
     ...
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125