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.
Add the space to the character class:
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: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.