How to Deal with Apostrophes/Single Quotes in PHP when using preg_match

Validating First and Last Names with Single Quote Marks with PHP

So you’re happily coding along, setting up your data validation, when you realize that you suddenly cannot validate the name “John O’Neil”—what gives? Maybe you’ve added the single quote to your regular expression already or maybe you’re still trying to figure out how to do so. I’m going to assume that your data validation already works perfectly—if it doesn’t, then you need to get it to a point where it works.

Potential Problem 1 — Get Rid of the Backslashes!

First, make sure that the variable you are testing does not have any unwanted backslashes escaping the the single quotes. You can do this with the stripslashes() function in PHP. Your code should look something like this:

$my_name_field = $_POST['name'];
$my_name_field = stripslashes($my_name_field);

If you use this method, remember that you may need to re-escape those quotes later on if you are doing something like putting the data into a database. You could also just use double quotes to put it into the database, this will eliminate the re-escaping issue.

Potential Problem 2 — Your Regex Might Be Wrong

When you put the single quote into your regex, escape it out with a backslash and then be sure to remember to change the surrounding quotes to double quotes if you were using single quotes. For example, a function which return true or false for a valid name including upper and lowercase ASCII letters, hyphens, periods, commas, spaces, and single quotes looks like this:

function validateName($name) {
     if (!preg_match("/^[A-Za-z\\-\\., \']+$/",$name)) {
          $isValid = false;
     } else {
          $isValid = true;
     return $isValid;

That should handle just about any valid English-language name. Of course, if you handle a lot of names with characters that fall outside of those specified, you’ll want to modify it to suit your needs.

Potential Problem 3 — What if You Can’t Get Rid of the Slash?

Maybe, for whatever reason, you can’t remove the escaping slash. If this is the case, just remove it in the above function instead of doing it in the main code. Assuming you are not passing the variable by reference, the slash remains in place in the variable you need, it’s just removed in the temporary variable within the function.

Alternatively, you could just add a backslash to your list of allowed characters… I’d try to avoid this, though… you never know what some malicious individual might come up with if you allow escaped characters into your input!

Still Doesn’t Work? — Hack It!

If the above doesn’t work and you can’t figure out why, use str_replace() within the function to just get rid of all the apostrophes, like this: str_replace("'","",$name). Make sure you just do it within the function and don’t pass it back to the main code, though, otherwise you’ll lose the apostrophe entirely.