首页 > 解决方案 > PHP拆分然后合并

问题描述

例如我有一个这样的字符串:

$string = 'eat|drink today|tomorrow';

从上面的字符串我想得到结果

eat today, eat tomorrow, drink today, drink tomorrow,

我必须做什么?我尝试使用拆分,但结果不太好。谢谢。

标签: phpsplit

解决方案


一种方法是利用explode & implode,正如我们在这里明确指出的(你知道值和大小),这将起作用。使用正则表达式可能是一种更快更好的方法来立即拆分第一个字符串,但这是乍一看想到的解决方案。

$string = 'eat|drink today|tomorrow';

// First split the string by the space between them, then by the pipe in separate arrays.
$removedSpace = explode(' ', $string);

// The action items.
$actions = explode('|', $removedSpace[0]);
// The periods/time of day items.
$dayPeriods = explode('|', $removedSpace[1]);

$final = [];

// Loop through actions and for each day period, generate the string.
foreach ($actions as $action) {
    foreach ($dayPeriods as $dayPeriod) {
        $final[] = $action . ' ' . $dayPeriod;
    }
}

$finalString = implode(', ', $final); // Your desired result in string format without last comma.

[编辑] 第一个回复发表时,我正在写我的回复。随意删除这个。[/编辑]


推荐阅读