In article <4ece601a$0$28675$a8266bb1(at)newsreader(dot)readnews(dot)com>,
Denis McMahon <denismfmcmahon(at)gmail(dot)com> wrote:
> On Thu, 24 Nov 2011 08:39:17 +0100, Sandman wrote:
>
>> So, I have a list of phone numbers in various formats I.e. the users
>> have written them in different styles, with and without dashes, spaces
>> and so on.
>>
>> Now I want to format them. I have a text file with all the area codes
>> for Sweden, so I remove any non-digit character from the phone number
>> and then I parse out the area code. I am now left with the phone number.
>> An example:
>>
>> In-data: 0703051947
>> Parse out area code: 070
>> Phone number: 3051947
>>
>> Now, 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
>>
>> With me so far? What I don't know is exactly how to do it. This is my
>> code thus far:
>>
>> $number = "3051947";
>> foreach ($formats as $f){
>> $chars = strlen(preg_replace("/[^#]/", "", $f));
>> }
>
> Not sure why you want to use preg_replace for this
>
> switch(strlen($number)) {
> case 5: $chars = substr($number,0,3) . " " . substr($number,3,2); break;
> case 6: $chars = substr($number,0,2) . " " . substr($number,2,2) . " " .
> substr($number,4,2); break;
> case 7: $chars = substr($number,0,3) . " " . substr($number,3,2) . " " .
> substr($number,5,2); break;
> default: // handle any unexpected number lengths
> }
>
> Some code purists say that you should use multiple if / if else / else
> instead of switch, make your own mind up.
>
> $digits = strlen($number);
> if ($digits == 5) {
> $chars = substr($number,0,3) . " " . substr($number,3,2);
> }
> else if ($digits == 6) {
> $chars = substr($number,0,2) . " " . substr($number,2,2) . " " . substr
> ($number,4,2);}
> else if ($digits == 7) {
> $chars = substr($number,0,3) . " " . substr($number,3,2) . " " . substr
> ($number,5,2);
> }
> else {
> // handle any unexpected number lengths
> }
>
> Rgds
>
> Denis McMahon
That... totally removed my handy array of formats :)
I kind of want that one :)
--
Sandman[.net]
|