tags:

views:

42

answers:

3

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?

+1  A: 

Just add it to the character class:

'/^[a-zA-Z0-9&\'\s-]+$/'
SilentGhost
That dosen't match
morpheous
of course it does. what are you talking about?
SilentGhost
Hold on, I suspect I did not reload my page during testing. I'll try again
morpheous
Yup, I made a silly mistake, I edited the wrong regex in the file. Problem sorted.
morpheous
A: 

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

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

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]+$/'
Marcelo Cantos