jcanker Posted March 3, 2010 Share Posted March 3, 2010 I'm trying to learn more about RegEx and preg_* functions. In this particular code I am working with a preexising code & db, wherein the db stores a phone number in one column, but the php code takes the phone number in three form INPUT blocks, and it isn't properly parsing the phone number back into each block. I want to replace the 3 form input areas with one, but I want to ensure that any spaces, dashes, or parentheses are removed so that it's just the digits of the phone number. Later when the phone number is just displayed as part of the customer info (ie, not in an "edit info form," I want to add the dashes back. Question 1: Is this the proper use of preg_replace() to get rid of any character that is not a digit? $phone = preg_replace(/D,"",$phone); Question 2: Can I nest substr_replace to add dashes back in one line?: $phone_display = substr_replace(substr_replace($phone, "-",-4,0),"-",-7,0); Link to comment https://forums.phpfreaks.com/topic/194025-regex-validation/ Share on other sites More sharing options...
MatthewJ Posted March 3, 2010 Share Posted March 3, 2010 The proper regex for the first question would be $phone = preg_replace("/[^\d]/","",$phone); Then to put them back you just had one substr position in the wrong place $phone_display = substr_replace(substr_replace($phone, "-",-4,0),"-",-8,0); Or all together $phone = '(555)888.9999'; $phone = preg_replace("/[^\d]/","",$phone); $phone_display = substr_replace(substr_replace($phone, "-",-4,0),"-",-8,0); echo $phone_display; Link to comment https://forums.phpfreaks.com/topic/194025-regex-validation/#findComment-1021043 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.