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
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

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.