doudu7626
doudu7626
2014-12-29 03:13
浏览 29
已采纳

带有空格,下划线,短划线和圆点的php中的preg_match [重复]

This question already has an answer here:

I am trying to match a regular expression in PHP, using the following code.

if (!preg_match("/^[a-zA-Z0-9-_.]*$/",$string)) { 
  // Show error
 }

I want to allow

  • Integers (0-9)
  • Characters (small letters and capital letters) (a to z and A to Z)
  • Dots ( . )
  • Underscore ( _ )
  • Dash ( - )
  • Space ( )

It does not work. Does anyone have any suggestions for what I am doing wrong?

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doubaoguo7469
    doubaoguo7469 2014-12-29 03:25
    已采纳

    You should use:

    if (!preg_match("/^[\w\s\.-]*$/",$string)) {
        #show error
    }
    

    It will also match empty string because of '*'.

    点赞 评论
  • dty98339
    dty98339 2014-12-29 03:21

    You're practically there.

    if (preg_match('/^[a-zA-Z0-9-_. ]*$/', $string) !== 1) {
      // Show error
    }
    

    Assuming you want to allow empty strings. Otherwise, change * to +.

    点赞 评论

相关推荐