带有空格,下划线,短划线和圆点的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>

You should use:

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

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

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