Forum Moderators: coopster

Message Too Old, No Replies

A better way to concatenate hyphens to a phone number

         

ramoneguru

11:36 pm on Apr 23, 2005 (gmt 0)

10+ Year Member



I have this function that accepts a phone number in this format: 9167898787 and convert it to this format 916-789-8787. I think it is rather lame/ugly. Any ideas to make it better overall? By better I mean just different/quicker ways.

I already check the input to make sure it is 10 digits long and all integers.

function getPhoneNumber($someValue)
{
$phoneNumber = "$someValue";

$i = 0;
while ( $i < 10)
{
if ($i == 3 ¦¦ $i == 6)
$totalNumber .= "-";

$totalNumber .= $phoneNumber{$i};
$i++;
}

return $totalNumber;

}//end getPhoneNumber

ergophobe

1:03 am on Apr 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I suspect this would be faster, but either way the speed doesn't matter at all here unless you're processing thousands of numbers. With just one it's hardly going to be a bottleneck either way.

$phone = substr($val, 0, 3) . '-' . substr($val, 2, 3) . '-' . substr($val, -4);

ramoneguru

5:51 am on Apr 24, 2005 (gmt 0)

10+ Year Member



Cool.
--Nick

mcibor

9:30 pm on Apr 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I found an interesting function at [pl2.php.net...]

function string_format($format, $string, $placeHolder = "#")
{
$numMatches = preg_match_all("/($placeHolder+)/", $format, $matches);
foreach ($matches[0] as $match)
{
$matchLen = strlen($match);
$format = preg_replace("/$placeHolder+/", substr($string, 0, $matchLen), $format, 1);
$string = substr($string, $matchLen);
}
return $format;
}

To Use:

print string_format("(###)###-####", "4015551212");
will print out:
(401)555-1212

Hope it's of some use to you
Michal Cibor