tags:

views:

81

answers:

2

How do I make the following regular expression accept only the symbols I want it to accept as well as spaces?

if(!preg_match('/^[A-Z0-9\/\'&,.-]*$/', $line))
{
    die();
}
else
{
    //execute the rest of the validation script
}

I want the user to only be able to enter A-Z, 0-9, forward slashes, apostrophes, ampersands, commas, periods, and hyphens into a given text field $line.

It currently will accept something along the lines of HAM-BURGER which is perfect, it should accept that. I run into an issue when the user wants to type HAM BURGER (<- note the space).

If I remove the ^ from the beginning and/or the $ from the end it will succeed if the user types in anything. My attempted remedy to this was to make the * into a + but then it will accept anything as long as the user puts in at least one of the acceptable characters.

+6  A: 

Add the space to the character class:

if(!preg_match('/^[A-Z0-9\/\'&,. -]*$/', $line))

Yes, it's that simple.

Note that the space has to be inserted before the - because it is a metacharacter in a character class (unless it's the first or last character in said character class). Another option is to escape it like:

if(!preg_match('/^[A-Z0-9\/\'&,.\- ]*$/', $line))

The regex explained:

  • ^ and $ are start and end of string anchors. It tells the regex engine that it has to match the whole string rather than just part of it.

  • [...] is a character class.

  • * is the zero-or-more repetition operator. This means it will accept an empty string. You can change it to + (one-or-more) so it rejects the empty string.

Confluence
Match `.` to ` ` or match `.`, ` ` and `-` ?
BrunoLM
Or if you want to include any whitespace -- including spaces or tabs -- add the '\s' character in place of a space. Also you are using * at the end, which means it will match any amount of these characters -- from 0 on -- so a blank string will match.
Chris Forrette
@Bruno Obrigado, eu corrigi o problema.
Confluence
Thank you! I figured it was something that simple, I just didn't want it to be a horrible security hole, a practice that was frowned upon or a soon to be deprecated methodology.
Eric
A: 

This is a good reference for RegEx, though specifically for Perl:

http://www.cs.tut.fi/~jkorpela/perl/regexp.html

hisabness