FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » Phone number formatting
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: Phone number formatting [message #176122 is a reply to message #176114] Thu, 24 November 2011 13:22 Go to previous messageGo to previous message
Sandman is currently offline  Sandman
Messages: 32
Registered: August 2011
Karma:
Member
In article <jal3k2$61m$1(at)dont-email(dot)me>,
"Álvaro G. Vicario" <alvaro(dot)NOSPAMTHANX(at)demogracia(dot)com(dot)invalid>
wrote:

> El 24/11/2011 8:39, Sandman escribió/wrote:
>> I have an array with formattings, that looks like this:
>>
>> $formats = array("### ##", "## ## ##", "### ## ##");
>>
>> The phone number above is never more than 7 digits long (as far as I
>> know) in Sweden, so these formats should suffice. Let me explain, in
>> the array, we have formats for 5, 6 and 7 digit phone numbers, set up
>> in a specific way. So this phone number in my example above is 7
>> digits, so it should be formatted as such:
>>
>> 305 19 47
>
> It's an interesting problem. I've came up with this proof of concept:
>
> function format_phone_number($number){
> $formats = array(
> 5 => "### ##",
> 6 => "## ## ##",
> 7 => "### ## ##"
> );
>
> $len = strlen($number);
>
> if( isset($formats[$len]) ){
> $format = strtr($formats[$len], array('#' => '%s'));
> $digits = str_split($number);
> return vsprintf($format, $digits);
> }else{
> return $number;
> }
> }
>
> Basically, it converts your expression into a printf-compatible format.
>
> Of course, it'd be easier to use such expression from the beginning:
>
> function format_phone_number($number){
> $formats = array(
> 5 => "%s%s%s %s%s",
> 6 => "%s%s %s%s %s%s",
> 7 => "%s%s%s %s%s %s%s"
> );
>
> $len = strlen($number);
>
> if( isset($formats[$len]) ){
> $digits = str_split($number);
> return vsprintf($formats[$len], $digits);
> }else{
> return $number;
> }
> }
>
> You could replace %s with %d if you validate that $number is an integer.

Thank you! Your suggestions sparked some ideas that I followed,
especially the printf-friendly conversion. I also changed the formats
to include the area code, as such:

"A-## ## ##"

And replaced it all to

"%s-%s%s %s%s %s%s"

%s is necessary since %d will strip leading zeroes.


--
Sandman[.net]
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: session handler auto log out
Next Topic: Stats comp.lang.php (last 7 days)
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Fri Nov 22 09:32:36 GMT 2024

Total time taken to generate the page: 0.04103 seconds