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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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!

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.