0

I want to separate numbers by a space, in sets of 4. e.g. 1234567890, would become 1234 5678 90

I managed to create a script to achieve this, but it seems over the top, is there any easier way of achieving this?

$num = 23853267362365;
$count = strlen($num)/4;

$new_num = array();
for ($x = 1; $x <= $count; $x++) {
    $num_len = strlen($num);
    if($num_len>4) {
        $new_num[] = substr($num,0,4);
        $num = substr($num,4,$num_len-4);
    }
}

$num = implode(' ',$new_num);
2
  • 1
    preg_replace('/(\d{4})/', '$1 ', $str)? Commented Sep 13, 2016 at 21:45
  • @MarcB: If string is divisible by 4 you'll get a trailing space. Commented Sep 13, 2016 at 21:55

2 Answers 2

3

chunk_split():

echo chunk_split(1234567890, 4, ' ');

Link: http://php.net/manual/function.chunk-split.php

Sign up to request clarification or add additional context in comments.

Comments

0

A non chunk_split() answer; not as good as Jessie Jackson's answer but is adaptable to any chunk length.

$start_num = 23853267362365;
$chunk_length = 4; // change to whatever length you need
$count = ceil(strlen($num) / $chunk_length);

$concat =''; // initiate
for ($x = 0; $x < $count; $x++) {
   $concat .= substr($start_num, ($chunk_length * $x), $chunk_length) . ' ';
}

$new_num = rtrim($concat, ' ');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.