问题
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.
回答1:
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.
回答2:
That you can do:
\w
stand for[a-zA-Z0-9_]
- 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 - 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
...
来源:https://stackoverflow.com/questions/17057390/regular-expression-for-alpha-numeric-space-dash-and-hash