Nimesh Madushan
Nimesh Madushan

Reputation: 13

Add spaces into string dynamically in PHP

I want to put a "-" after every three numbers.
For example:

$number = 123456789;

I want to make it as 123-456-789;

Can someone give me a help?
Thanks.

Upvotes: 1

Views: 1374

Answers (5)

M.J.Ahmadi
M.J.Ahmadi

Reputation: 3931

This will serve your wish :)

echo trim(chunk_split('123456789', 3, '-'),'-');

Upvotes: 1

Rajeev Ranjan
Rajeev Ranjan

Reputation: 4142

look at this solution also no line breaks after "-"

$output = wordwrap($inputstring, 3, "-&nbsp" , true);
echo $output;

Upvotes: 0

May Ann
May Ann

Reputation: 11

Use word wrap with the following:

$orig = "123456789";
$str = wordwrap($orig, 3, "-\n" , true);
echo $str;    

Upvotes: 0

DevZer0
DevZer0

Reputation: 13535

Split the string to array and glue it back using str_split

$string = "12345678645465665646346";
 $arr = str_split($string, 3);
 $output = implode("-", $arr);
echo $output;

Upvotes: 2

user1864610
user1864610

Reputation:

You can use chunk_split():

$number = "123456789";
$phone = chunk_split($number,3,"-");
$phone = substr($phone, 0, -1);  // remove trailing hyphen

Upvotes: 5

Related Questions