0

I have the following Regex (in PHP) that I am using.

'/^[a-zA-Z0-9&\'\s]+$/'

It currently accepts alpha-numerics only. I need to modify it to accept hyphens (i.e. the character '-' without the quotes obviously) as well.

So it will accept strings like 'bart-simpson' OR 'bond-007' etc.

Can anyone explain how to modiy the pattern?

4
  • a regex like this '/^[-a-zA-Z0-9&\'\s]+$/' , will make it possible to create strings like: "----" or "-something"... is this the desired behaviour? what kind of strings do you expect? do you have limitations or everything within those characters is allowed?? Commented May 13, 2010 at 10:43
  • @acmatos: and the existing regex matchs "&&&' &", so what is your point? Commented May 13, 2010 at 10:44
  • it currently accepts ampersand, single quote and whitespace characters apart from alphanumerics. Commented May 13, 2010 at 10:46
  • I don't have a point, just asking if that's the desired behaviour for the regex... The examples look like usernames to me so, I wouldn't want a user with ampersands, quotes, whitespaces or - but that's me. :-) Commented May 13, 2010 at 10:51

3 Answers 3

1

Just add it to the character class:

'/^[a-zA-Z0-9&\'\s-]+$/'
Sign up to request clarification or add additional context in comments.

2 Comments

Hold on, I suspect I did not reload my page during testing. I'll try again
Yup, I made a silly mistake, I edited the wrong regex in the file. Problem sorted.
0

Just add a hyphen at the end of the character group within brackets. This ought to work:

'/^[a-zA-Z0-9&\'\s-]+$/'

Comments

0

I add the hyphen at the front, to make it fairly obvious that it isn't part of a range:

'/^[-a-zA-Z0-9&\'\s]+$/'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.