Jump to content

Problems with preg_match and user input that contains parenthesis


cyberRobot

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
}
?>

Archived

This topic is now archived and is closed to further replies.

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