1

How to split this string :

56A19E6D77828 

into format like this :

56A1 9E6D 7782 8 

Are there any native PHP functions built for this?

4 Answers 4

9

You can use str_split()

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

Outputs:

56A1 9E6D 7782 8 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

0

Version without temporary array:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.