Jump to content

Problems with preg_match and user input that contains parenthesis


Recommended Posts

I'm using preg_match to compare new user input to an existing database entry. What I have works for the most part but I ran into an issue when that user input contains special characters like parenthesis.

 

Is there a function available to escape these characters? Or maybe there's a way to tell PHP to treat what's inside a variable as text only?

 

 

For example, here is a simplified version of what I was using to test a phone number:

 

if(preg_match("/^$newPhoneNum$/i", $databasePhoneNum)) {
    //DO NOTHING
} else {
    //CREATE A BUTTON THAT UPDATES THE DATABASE
}

 

 

The above code doesn't work if $newPhoneNum is equal to "(888)888-8888" due to the parenthesis. So I modified the code to be:

 

$newPhoneNum         = preg_replace("/[^a-zA-Z0-9]/", '', $newPhoneNum);
$databasePhoneNum = preg_replace("/[^a-zA-Z0-9]/", '', $databasePhoneNum);
if(preg_match("/^$newPhoneNum$/i", $databasePhoneNum)) {
    //DO NOTHING
} else {
    //CREATE A BUTTON THAT UPDATES THE DATABASE
}

 

The new code not only solved the issue with parenthesis, but it also matches phone numbers like "888-888-8888", "(888) 888-8888", etc. :D

 

 

But I still could have problems with the other fields (name, address, etc.). Is there another solution that I'm missing, or do I need to keep using things like preg_replace to remove troublesome characters? :-\

preg_quote() is made for this :) And remember to feed your delimiter as the second parameter.

 

Edit: But if you only want to do a case-insensitive comparison, the below will suffice (and be faster):

 

<?php
if (strtolower($newPhoneNum) == strtolower($databasePhoneNum)) {
//match
}
?>

 

or probably even

 

<?php
if (strcasecmp($newPhoneNum, $databasePhoneNum) == 0) {
//match
}
?>

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.