How do I allow spaces in this regex?

前端 未结 6 1356
渐次进展
渐次进展 2021-01-12 02:05

I\'m such an amateur at regex, how do I allow spaces(doesn\'t matter how many) in this regex?

if(preg_match(\'/[^A-Za-z0-9_-]/\', $str)) return FALSE;
         


        
6条回答
  •  误落风尘
    2021-01-12 02:57

    Your question is unclear. The regular expression, as it stands, will succeed if $str has any character in it that is not A-Za-z0-9_-. Since a space is not one of these characters, the regular expression will match, and the whole statement returns FALSE.

    If this isn't what you want, and you want your regular expression to match if $str has any character that is not in A-Za-z0-9_- or a space, then you need to change it to A-Za-z0-9_ - (note the space between the underscore and the hyphen). Thus when your string has a character that is not A-Za-z0-9_ -, the regular expression will match, and your statement will return FALSE. If your string is made up entirely of A-Za-z0-9_ -, then the regular expression will fail to match, and your processing will continue to the next line.

    Edit: Here's an example: If your string is abc123def, currently the regular expression will not match and you will not return FALSE. If your string is abc123 def, the regular expression will match and the statement will return FALSE. If you change the character class to A-Za-z0-9_ -, then the regular expression will fail to match for both abc123def and abc123 def, and you will not return FALSE.

提交回复
热议问题