cyberRobot Posted January 5, 2010 Share Posted January 5, 2010 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. 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? :-\ Link to comment https://forums.phpfreaks.com/topic/187277-problems-with-preg_match-and-user-input-that-contains-parenthesis/ Share on other sites More sharing options...
thebadbad Posted January 5, 2010 Share Posted January 5, 2010 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 } ?> Link to comment https://forums.phpfreaks.com/topic/187277-problems-with-preg_match-and-user-input-that-contains-parenthesis/#findComment-988969 Share on other sites More sharing options...
cyberRobot Posted January 5, 2010 Author Share Posted January 5, 2010 Thanks for the excellent tips. I'm not sure why I didn't think about using strtolower(). I'll most likely switch to that. Link to comment https://forums.phpfreaks.com/topic/187277-problems-with-preg_match-and-user-input-that-contains-parenthesis/#findComment-988991 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.