Page 1 of 1
Validating phone Singaporean number
Posted: Sun May 11, 2008 9:28 am
by LonelyProgrammer
Hi all,
The Singaporean phone number format starts with either a 8,6 or 9, and is followed by 7 digits. I tried this regex, but it does not work. Where did I go wrong?
Code: Select all
preg_match('/'^[9|6|8]\d{7,7}$'/i', '91111111 ', $result);
Thanks!
Re: Validating phone Singaporean number
Posted: Sun May 11, 2008 9:44 am
by GeertDD
Even though the regex itself is not that nicely written, it will match the phone numbers. However, look at the quotes around the pattern. I would be surprised if they do not result in a parse error.
Here is a cleaned up version:
Code: Select all
preg_match('/^[689]\d{7}$/D', '91111111', $result);
Re: Validating phone Singaporean number
Posted: Sun May 11, 2008 9:57 am
by LonelyProgrammer
Thanks...it was originally a non-PERL compatible regex and I tried to convert it to one. Looks like I have done a clumsy job at that.
Re: Validating phone Singaporean number
Posted: Mon May 12, 2008 11:53 am
by prometheuzz
LonelyProgrammer wrote:Thanks...it was originally a non-PERL compatible regex and I tried to convert it to one. Looks like I have done a clumsy job at that.
FYI, character classes always match one character and the "normal" regex meta characters don't apply inside them, so your:
[9|6|8] matches either a '9', a '6', a '8' or a '|' (!), since the pipe-char has no meaning inside it.
Note that
[968] is the same as
(9|6|8), although when matching only one character, the first is preferred by many.
And your
\d{7,7} is perfectly valid, but as already pointed out, the second 7 is not necessary.
So, all in all, you were pretty close! ; )
Re: Validating phone Singaporean number
Posted: Mon May 12, 2008 1:58 pm
by GeertDD
prometheuzz wrote:Note that [968] is the same as (9|6|8), although when matching only one character, the first is preferred by many.
The first one is also faster.
Re: Validating phone Singaporean number
Posted: Mon May 12, 2008 2:19 pm
by prometheuzz
GeertDD wrote:prometheuzz wrote:Note that [968] is the same as (9|6|8), although when matching only one character, the first is preferred by many.
The first one is also faster.
Albeit barely noticeable in this case.
The more important thing, IMO, is the readability of the regex (again: in this case, there are occasions when you'll have to take speed into consideration, of course).
Re: Validating phone Singaporean number
Posted: Mon May 12, 2008 3:57 pm
by GeertDD
Yeah, the readability of [968] is much better too.