将两端带有" 标记的数组元素组合在一起



我需要组合两个或多个括在双引号内的数组元素... 例: -以前-

[
"Foo1",
""Foo2",
"Foo3",
"Foo4"",
"Foo5"
]

-后-

[
"Foo1",
""Foo2 Foo3 Foo4"",
"Foo5"
]

下面,$source$result分别是来源和结果。我会使用array_reduce()

$result = array_reduce($source, function($acc,$i) {
static $append = false; // static so value is remembered between iterations
if($append) $acc[count($acc)-1] .= " $i"; // Append to the last element
else $acc[] = $i; // Add a new element
// Set $append=true if item starts with ", $append=false if item ends with "
if(strpos($i,'"') === 0) $append = true;
elseif (strpos($i,'"') === strlen($i)-1) $append = false;
return $acc; // Value to be inserted as the $acc param in next iteration
}, []);

现场演示

function combine_inside_quotation($array)
{
if(!is_array($array) || 0 === ($array_lenght = count($array))) {
return [];
}
$i = 0;
$j = 0;
$output = [];
$inside_quote = false;
while($i < $array_lenght) {
if (false === $inside_quote && '"' === $array[$i][0]) {
$inside_quote = true;
$output[$j] = $array[$i];
}else if (true === $inside_quote && '"' === $array[$i][strlen($array[$i]) - 1]) {
$inside_quote = false;
$output[$j] .= ' ' . $array[$i];
$j++;
}else if (true === $inside_quote && '"' !== $array[$i][0] && '"' !== $array[$i][strlen($array[$i]) - 1]) {
$output[$j] .= ' ' . $array[$i];
} else {
$inside_quote = false;
$output[$j] = $array[$i];
$j++;
}
$i++;
}

return $output;
}

试试这个函数,它会给出你提到的输出。

现场演示

最新更新