Forum Moderators: coopster

Message Too Old, No Replies

preg match not recognizing apostrophe

         

max4

11:58 pm on Apr 30, 2009 (gmt 0)

10+ Year Member



Hello,

I am working on a form submission process and would like to check if a user has entered a valid name. By valid, I mean the name contains upper and lowercase letters, hyphens, spaces and apostrophes. I'm using this to validate the name feild:

if (!preg_match("/^[a-zA-Z'- ]+$/",$fullName) ¦¦ strlen($fullName) < 3 ¦¦ strlen($fullName) > 32) {
$invalidName = 1;
header("Location: login.php?invalidName=1");
}

This works for names like Bob Smith, or Ahmed Al-Mahdi, but will not work for names such as John O'Connor. The apostrophe returns the invalidName error. Any suggestions?

Thanks,
Max

rocknbil

3:09 pm on May 1, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



'John O'reilly'

Note that this is not a php error, it'sa mysql error. MySQL thinks your field value ended at "O' " and doesn't know what to do with the rest of it.

It's a matter of style. If you're always going to single-quote mysql values, simply double them up:

$field = preg_replace("/'+/","''",$field);

Which gives you this:

'John O''reilly'

Weird huh? But when it inserts it will insert properly:

John O'reilly

Same is true if you want to query:

$term = "John O'reilly";
$term = preg_replace("/'+/","''",$term);

$q = "select * from table where lname='$term';

Will work fine.

eeek

11:55 pm on May 1, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



$term = preg_replace("/'+/","''",$term);

Please don't use that to escape strings for mysql. There's a supplied function to do that job.

eelixduppy

7:01 pm on May 2, 2009 (gmt 0)




There's a supplied function to do that job.

[php.net...]

This 33 message thread spans 2 pages: 33