Re: regular expressions and Phone validation
| From: | Rafael | Date: | Thu, 16 Mar 2006 06:55:56 +0000 |
| Subject: | Re: regular expressions and Phone validation | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-232002@lists.php.net to get a copy of this message | ||
Paul Goepfert wrote:
I have one small problem I don't understand the preg_replace() method. I understand the gist of what it does but I still don't fully know what it does. I have read the entry in the php manual about this and I am still confused about it. I've never been any good with regular expressions.Well, I'm not sure about what you don't understand. Anyway, preg_replace() does "the same" as str_replace(), but using regular-expressions instead of just strings. If you understand how do reg-exp work, then it should have no real problem, if the reg-exp are the problem then you better read a little more about them (the PCRE tutorial at php.net is really good, IMHO)
Here is the function in use: function checkPhone ($Phone) [···]
$Phone = ereg_replace("[^0-9]", '', $Phone);
if ((strlen($Phone)) <= 14)
return preg_replace("/[^0-9]*([0-9]{3})[^0-9]*([0-9]{3})[^0-9]*([0-9]{4}).*/",
"(\\1) \\2-\\3", $Phone);
[···]
I think my problem is mostly what is returned when preg_replace executes?Well, what's inside parenthesis is "remembered" by preg_replace(), and you make reference to them using "\\n" or "$n" (where "n" is a number) in the "replace-string" (there are some exceptions, but that should do for now) If you look carefuly, there are three expressions between parenthesis, and these are what you're referencing via "(\\1) \\2-\\3" Though, there's something I don't get it: in your reg-exp your ignoring any non-numeric character, but you already got rid of them with ereg_replace()... (??) -- Atentamente, J. Rafael Salazar Magaña Innox - Innovación Inteligente Tel: +52 (33) 3615 5348 ext. 205 / 01 800 2-SOFTWARE http://www.innox.com.mx