tags:

views:

59

answers:

2

Would this be the correct regexp to allow A-Z a-z 0-9 and symbols #&()-\;,.'" and spaces?

I'm struggling with the ' and " inside the regexp. Is what I've done correct? Note the \' and \". It just doesn't seem right. Whats the right way to do it?

if (preg_match('/^[a-z0-9#&()-\;,.\'\" ]+$/i', $username) )   
{   
    echo "Good";   
}   
else   
{   
    echo "Bad";   
} 
+2  A: 
John Kugelman
I kept getting : Warning: preg_match() [function.preg-match]: No ending delimiter '^'. So i did '/^[a-z0-9#,.\'" ]+$/i' Note the / at the beginning. Is this right?
Norman
Yes, my bad. I lost your starting slash when I copy-and-pasted.
John Kugelman
The semicolon does not need to be escaped at all.
Gumbo
@Gumbo I agree. The OP is trying to match a literal backslash, and happened to place it before the semi-colon in his regex.
John Kugelman
Before I go :), the right way to allow new lines (the enter key) in the regexp above would be like this, right? '/^[a-z0-9#,.\'"\r\n ]+$/i' I added \r\n. No harm if done this way?
Norman
Yes, that's right. You can also use `\s` as a shorthand for all whitespace if tabs are okay too.
John Kugelman
A: 

Brackets also needed to be escaped

'/^[a-z0-9#&\(\)\-;,.\'" ]+$/i'
Maulik Vora
Incorrect. Parentheses are not special inside character classes.
Ben Blank
This answer too gives me the error : preg_match() [function.preg-match]: No ending delimiter '^' found in...
Norman