CyberJunkie
CyberJunkie

Reputation: 22674

Help with php regex for limiting allowed characters

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

Answers (5)

Phil
Phil

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.

Edit

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

Mike Pennington
Mike Pennington

Reputation: 43077

Please use /^[a-z,0-9+\#\-,\s]+$/i

Upvotes: 1

alex
alex

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

anubhava
anubhava

Reputation: 784888

Use this regex:

/^[-a-z0-9,# ']+$/i

Upvotes: 0

manojlds
manojlds

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

Related Questions