Jump to content

[SOLVED] how to split phone numbers


web_master

Recommended Posts

hi,

 

how can I split a phone number from dbase?

 

 

<?php 
$query_return = mysql_query("SELECT * FROM `sms_txt` ORDER BY `sms_txt_id` DESC");

while($request = mysql_fetch_array($query_return)) {
   print $request['sms_txt_phonenr'];
}

?>

 

in this case I got this:

 

381631234567

 

(381 = country code, 6 = area code, 1234567 = phone nr)

 

BUT

 

I want to look like this

 

(063) 123-4567

 

thnx in advanced!

 

Link to comment
https://forums.phpfreaks.com/topic/119688-solved-how-to-split-phone-numbers/
Share on other sites

<pre>
<?php
$num = '381631234567';
echo preg_replace('/\A\d{3}(\d{2})(\d{3})(\d{4})\z/e', 'sprintf("(%03d) %3d-%4d", $1, $2, $3)', $num);
?> 
</pre>

 

Absolutely elegent! You've done regular expressions before, haven't you? I can tell!  ;)

 

Cheers,

 

NRG

for the record, there is a non-regex method

 

<?php
$num = '381631234567';
list ($a, $b, $c, $d) = sscanf($num, '%3s%2s%3s%4s');
echo "(0$b) $c-$d";
?>

 

Wow.. that is really efficient looking. But I am confused.

I understand that the list is taking the first 3 characters and storing it as $a, the next two characters as $b, and so forth..

What I'm not sure about is the (0$b) part.. how does that manage to put $a in brackets?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.