Reputation: 5525
How to split this string :
56A19E6D77828
into format like this :
56A1 9E6D 7782 8
Are there any native PHP functions built for this?
Upvotes: 1
Views: 2294
Reputation: 21
Version without temporary array:
$number = '56A19E6D77828';
echo trim(chunk_split($number, 4, ' '));
Upvotes: 0
Reputation: 1545
If anyone needs to split different numbers for each split and then join them together, It's super hacky but this works, had to split a gift card that gets rendered.
$card = "603628385592165882327";
$test = str_split($card, 6);
$test1 = str_split($card, 5);
$test2 = str_split($card, 6);
$test3 = str_split($card, 4);
$number = $test[0];
$number .= " ";
$number .= $test1[1];
$number .= " ";
$number .= $test2[2];
$number .= " ";
$number .= $test3[3];
echo $number;
result
603628 83855 165882 1658
Upvotes: 0
Reputation: 47992
For your sample input, this task can be completed with one function call and without generating a temporary array.
$string = '56A19E6D77828';
var_export(preg_replace('~.{4}\K~', ' ', $string)); // '56A1 9E6D 7782 8'
If you need to be careful to not add an extra trailing space when the string length is a factor of four, then just check that you haven't reached the end of string anchor.
$string = '56A19E6D77828333';
var_export(preg_replace('~.{4}\K(?!$)~', ' ', $string)); // '56A1 9E6D 7782 8333'
The pattern is simple:
.{4}
)\K
)(?!$)
No string explosions or array implosions, just direct string manipulation.
Upvotes: 0
Reputation: 2631
You can use str_split()
$card = "56A19E6D77828";
echo join(" ", str_split($card, 4));
Outputs:
56A1 9E6D 7782 8
Upvotes: 9