Jump to content

[SOLVED] regex to only include letters, spaces hyphens and apostrophes


ashleek007

Recommended Posts

Hi All,

 

This is really bugging me.... I basically just want the regex for a name field in my form... as a check to make sure no user has input stupid characters...

 

so the ones i would like are: -

 

[a-z] and [A-Z] and 'spaces' and 'hyphens' and 'apostrophes'

 

im currently using it as part of a preg_match and dont know the syntax of it all: -

 

this is what ive got : -

 

preg_match("/[a-z]+[A-Z]+/", $USER_VARS['FORE'])

 

can someone throw a light on it at least?

Cheers,

Ash

sorry it does seem to do what I wanted... just need to put a ! infront of the preg_match for my purpose...

 

I've just realised though that my DB doesnt like apostrophes... is this normal?

 

preg_match("/^[a-z -]+\z/i", $USER_VARS['FORE']);

 

would that be the code if I didnt want to allow apostrophes??

 

Cheers,

Ash

I've just realised though that my DB doesnt like apostrophes... is this normal?

This is because you need to escape apostrophes before you insert into your DB. So, you'll need to run your string through mysql_real_escape_string() to clean it up before your actual INSERT statement. Read upon SQL Injection to see why this is such an issue.

 

preg_match("/^[a-z -]+\z/i", $USER_VARS['FORE']);

 

would that be the code if I didnt want to allow apostrophes??

 

Sure is. Here's a quick overview of what the code is doing:

/      = starting delimiter for my regexp
^      = match starting at the beginning of the string
[      = start a character set
a-z '- = alpha characters, spaces, apostrophes and dashes
]      = end the character set
+      = must have one or more of the character set defined
\z     = match ending at the end of the string
/      = ending delimiter for my regexp
i      = declares this as a case INsensitive search

 

 

Hope this helps!

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.