Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I allow spaces in this regex?

Tags:

regex

php

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;
like image 555
soren.qvist Avatar asked Jan 25 '11 19:01

soren.qvist


People also ask

How do you put a space in regex?

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

How do I allow blank space in regex?

\s is the regex character for whitespace. It matches spaces, new lines, carriage returns, and tabs.

What does \b mean in regex?

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

What does \\ mean in regex?

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.


1 Answers

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

like image 68
chaos Avatar answered Oct 12 '22 22:10

chaos