user3364963
user3364963

Reputation: 397

PHP Add Space Every 4th Character but ignore when you reach a comma

This is my line

AQUA19097444,AQUA43188766,AQUA49556282,AQUA51389151,AQUA57267110,BLUE12811521,BLUE15966728

This is what I want to achieve in the end

AQUA 1909 7444,AQUA 4318 8766,AQUA 4955 6282,AQUA 5138 9151,AQUA 5726 7110,BLUE 1281 1521,BLUE 1596 6728

Notice there is space every 4 characters but does not include a space if a comma is next.

This is what I have tried so far: note I am in a for each loop

$Raffles[$index] = chunk_split($Raffles[$index], 4, ' ');

This is the output of the code

AQUA 1909 7444 ,AQU A431 8876 6,AQ UA49 5562 82,A QUA5 1389 151, AQUA 5726 7110 ,BLU E128 1152 1,BL UE15 9667 28

As you can see it does a space when It reaches the comma which I want it to ignore

Please help me out and thank you for reading my question.

Upvotes: 0

Views: 203

Answers (3)

Jason Berresford
Jason Berresford

Reputation: 1

Something like the below should work...

    $string ='AQUA19097444,AQUA43188766,AQUA49556282,AQUA51389151,AQUA57267110,BLUE12811521,BLUE15966728';
    $explode = explode(',',$string);

    $count = 0;

    while (!empty($explode[$count])) {
        $var[] = chunk_split($explode[$count], 4, ' ');
        $count++;
    }

Upvotes: -1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

The complex way:

$Raffles[$index] = implode(",",array_map(function($p) {return chunk_split($p,4," ");},explode(",",$Raffles[$index])));

(Note that you can potentially do that without being in a foreach loop by wrapping another array_map around it)

The black magic way:

$Raffles[$index] = preg_replace("/([^,]{4})(?!,)(?=.)/","$1 ",$Raffles[$index]);

Upvotes: 4

Dan
Dan

Reputation: 9478

Explode your string, then loop through it and use chunk_split to place the space every fourth character.

$string = 'AQUA19097444,AQUA43188766,AQUA49556282,AQUA51389151,AQUA57267110,BLUE12811521,BLUE15966728';

$exploded_string = explode(',', $string);

foreach($exploded_string as $item){
    $result[] = chunk_split($item, 4, ' ');
}

print_r($result); will give you

Array ( [0] => AQUA 1909 7444 
        [1] => AQUA 4318 8766 
        [2] => AQUA 4955 6282 
        [3] => AQUA 5138 9151 
        [4] => AQUA 5726 7110 
        [5] => BLUE 1281 1521 
        [6] => BLUE 1596 6728 )

If you want to convert this back into a comma separated string use $result = implode(',', $result);

Upvotes: 2

Related Questions