-1

I am trying to validate a string (a name) using preg_match(). I am passing in a string called $lname which is a string containing an apostrophe which has been slashed. An example of this is "O\'Neill". I have tried multiple regex layouts and solutions for this including (\') , \' , and just '. It does not work and give a true output being valid. Can anyone offer a solution.

Here is my code:

$lname = "O\'Neill";
if(preg_match("/^[a-zA-Z\'\s-]+$/",$lname))
    echo "valid";

1 Answers1

0

Your first problem is not escaping the backslash. You'd need to write a literal backslash as \\ in regex.

However, if you just do that, you'd be looking for a backslash or apostrophe anywhere, not a sequential \' because of your [...] which matches any character inside.

The correct way to do this would be to look for it outside of the brackets.

^([a-zA-Z\s-]|\\')+$ 

http://regexr.com/3g7dm

Note: If you're doing this to protect your SQL queries, it's not the proper way. You should be using prepared statements.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95