Reputation: 22674
I'm working in php and want to set some rules for a submitted text field. I want to allow letters, numbers, spaces, and the symbols # ' , -
This is what I have:
/^(a-z,0-9+# )+$/i
That seems to work but when I add the '
or -
symbols I get errors.
Upvotes: 0
Views: 432
Reputation: 164732
Almost there. What you're looking for is called character classes. These are denoted by the use of square brackets. For example
/^[-a-z0-9+#,' ]+$/i
To include the hyphen character, it needs to be the first or last character in the class.
As you want to include the single quote and you're using PHP where regular expressions must be represented as strings, be careful with how you quote the pattern. In this case, you can use either of
$pattern = "/^[-a-z0-9+#,' ]+\$/i"; // or
$pattern = '/^[-a-z0-9+#,\' ]+$/i';
Upvotes: 4
Reputation: 490143
I want to allow letters, numbers, spaces, and the symbols
#
,'
,,
and-
.
Use this regex...
/^[-a-zA-Z\d ',#]+\z/
Note the \z
. If you use $
, you are allowing a trailing \n
. CodePad.
Ensure to escape the '
if you are using '
as your string delimiter.
Upvotes: 2
Reputation: 301037
You should use a character class - [a-zA-Z0-9 #',-]
Note that -
should be used first or last or escaped otherwise it gets treated as denoting a range and you will get errors
Upvotes: 2