user1286650
user1286650

Reputation: 1

Phone number output

I would like to print raw phone number record (31999999) as 31-999-999 (PHP). I have never done that before. Can anyone help me out?

Thanks

Upvotes: 0

Views: 243

Answers (3)

Madara's Ghost
Madara's Ghost

Reputation: 174957

<?php
$phone = 31999999;

$formatted_phone = preg_replace("|\b(\d{2})(\d{3})(\d{3})\b|", "$1-$2-$3", $phone);

echo $formatted_phone;

This is what I came up with, there might be simpler ways but this seem shortest. However, it will only accept an exact 8 digit number, nothing more nothing less. If you want a different pattern, you'll need to specify your input exactly.

Upvotes: 1

Cam
Cam

Reputation: 15234

We can take advantage of PHP's weak type system, so it doesn't matter if the number is stored as a string or not:

$num = 112223333;
echo substr($num,0,2) . "-" . substr($num, 2, 3) . "-" . substr($num, 4, 4); // 11-222-2333

edit: As per Oli's comment below, while it's of interest that this code works whether $num is a string or an int, for the sake of clarity and to avoid bugs you should store $num as a string.

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

You need to manipulate substrings in order to do this. Luckily, PHP has a substr() function.

Upvotes: 0

Related Questions