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 #176114 is a reply to message #176110] Thu, 24 November 2011 09:43 Go to previous messageGo to previous message
alvaro.NOSPAMTHANX is currently offline  alvaro.NOSPAMTHANX
Messages: 277
Registered: September 2010
Karma:
Senior Member
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.


--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://borrame.com
-- Mi web de humor satinado: http://www.demogracia.com
--
[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: Wed Nov 27 19:28:09 GMT 2024

Total time taken to generate the page: 0.03828 seconds