Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!news.musoftware.de!wum.musoftware.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Sandman Newsgroups: comp.lang.php Subject: Re: Phone number formatting Date: Thu, 24 Nov 2011 14:22:37 +0100 Lines: 75 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Trace: individual.net KW88nuB8BGVG0OHsM43olApnVmwZzOJrNhkvEPWF9yBv38puM= X-Orig-Path: mr Cancel-Lock: sha1:Ww8DK5YJB6Ac6TkKgA9Bnul61eo= User-Agent: MT-NewsWatcher/3.5.2 (Intel Mac OS X) X-Face: $@,Vfa$,)%=Qa7L]y)&oZj_\EiHc}}Af0Bei"4a_%)"c6TQ+P/:53>;PNGuWUmkqyeN-qM65foJ[;T_(k;>]&G\T4Lhm:2 ujye2_,iUJFE;NZn>y;.|-hl7g~bIOF1qG\o, "Álvaro G. Vicario" 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]