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;
\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.
\s is the regex character for whitespace. It matches spaces, new lines, carriage returns, and tabs.
The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).
The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes. Escaped character. Description. Pattern.
if(preg_match('/[^A-Za-z0-9_ -]/', $str)) return FALSE;
Note that I put the space before the hyphen. If the space were after the hyphen, I would be specifying a character range from underscore to space. (Issue also evadable by putting a backslash before the hyphen to escape it.)
This is assuming that what you mean by "allow" is: this regex is being used to validate a character string, and if it matches, then the character string is disallowed (hence return FALSE
). So the characters in the negated character class ([^...]
) are actually the allowed characters. (This is causing some general confusion in this question.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With