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;
the \s
in the regular expretion like this '/[^A-Za-z0-9_-\s]/'
mean the space
Not so much an answer to your question, but a site I find useful for checking regex expressions. It also explains what each part of the expression does / means as you hover over it in the input field.
You only need to add a literal blank space in your negated character class.
It would be more concise to use:
i
and omit one of the letter ranges[0-9]
as \d
like this:
if (preg_match('/[^A-Z0-9_ -]/i', $str)) return FALSE;
but even better would be to use \w
which represents [A-Za-z0-9_] (which is most of your pattern) to write:
if (preg_match('/[^\w -]/', $str)) return FALSE;
This pattern states that if $str
contains any character not in [A-Za-z0-9_ -]
then false
will be returned.
If you need to ALLOW only space you'll need '/ /'
If you need to ALLOW any whitespace char (space, tab, newline) - use '/\s/'
And if you need to add a space to your pattern (means to ignore space) - use /[^A-Za-z0-9_\ -]/
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
.
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.)