Saint Robson
Saint Robson

Reputation: 5525

How to add a space between every sequence of four characters (like a credit card number)?

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

Answers (4)

Vitalii Marenkov
Vitalii Marenkov

Reputation: 21

Version without temporary array:

$number = '56A19E6D77828';
echo trim(chunk_split($number, 4, ' '));

Upvotes: 0

Anders Kitson
Anders Kitson

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

mickmackusa
mickmackusa

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'

Demo Link

The pattern is simple:

  1. match any four characters (.{4})
  2. forget the match characters but retain the position (\K)
  3. check that the end of the string hasn't been met ((?!$)
  4. add the space to the position in the string

No string explosions or array implosions, just direct string manipulation.

Upvotes: 0

Michael
Michael

Reputation: 2631

You can use str_split()

$card = "56A19E6D77828";
echo join(" ", str_split($card, 4));

Outputs:

56A1 9E6D 7782 8

Upvotes: 9

Related Questions