Regular Expression for alpha numeric, space, dash, and hash

和自甴很熟 提交于 2019-12-11 10:29:21

问题


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:

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


来源:https://stackoverflow.com/questions/17057390/regular-expression-for-alpha-numeric-space-dash-and-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!