Search code examples
phpexplodeimplode

How to explode string in pair, two key by slice in PHP


$myvar1 = 'this car is most new and fast';
$myvar2 = explode(' ', $myvar1);  // slice on spaces
$myvar3 = implode( ',', $myvar2); //add comman
echo $myvar3;

output = this, car, is, most, new, and, fast

But I need this output = this car, is most, new and, fast

I need in pair output.

Thanks all.


Solution

  • $myvar1 = 'this car is most new and fast';
    preg_match_all('/([A-Za-z0-9\.]+(?: [A-Za-z0-9\.]+)?)/',
           $myvar1,$myvar2); // splits string on every other space
    $myvar3 = implode( ',', $myvar2[0]); //add comman
    echo $myvar3;
    

    Instead of explode(), I have used preg_match_all() to split the string and implode() with ',' And here is your output:

    this car,is most,new and,fast