Search code examples
phpexplode

PHP explode on second instance of a delimiter


I am trying to explode a string using PHP but when only if the second instance of the delimiter is detected before exploding it, for my case i want to explode it after the second space is detected.

My String

Apple Green Yellow Four Seven Gray

My desire output

Apple Green
Yellow Four
Seven Gray

My initial code

$string = 'Apple Green Yellow Four Seven Gray';
$new = explode(' ',$string);

How can i achieve this using explode or any separating method with PHP? thanks in advance!


Solution

  • Nice question - it can be done in many way. i came up with this 1 -

     $data='Apple Green Yellow Blue';
    
    
    $split = array_map(
        function($value) {
            return implode(' ', $value);
        },
        array_chunk(explode(' ', $data), 2)
    );
    
    var_dump($split);