如何在 PHP 中成对分解字符串,两个键按切片

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

但我需要这个输出=这辆车,最新,速度最快

我需要成对输出。

谢谢大家

$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;

而不是 explode(),我使用 preg_match_all() 来拆分字符串,并使用 implode() 和 ',' 这是你的输出:

this car,is most,new and,fast

应该这样做:

<?php
$str = 'this car is most new and fast';
$str_explode = explode(' ', $str);
$str_result = '';
$comma = false;

foreach($str_explode AS $word) {
    $str_result .= $word;

    if($comma === false) {
        $str_result .= ' ';
        $comma = true;
    } else {
        $str_result .= ', ';
        $comma = false;
    }
}

echo $str_result;

它使用一个布尔值,每个 运行 设置为 true 和 false,因此仅每隔一个单词显示逗号。