php - PHP拆分然后合并
问题描述
例如我有一个这样的字符串:
$string = 'eat|drink today|tomorrow';
从上面的字符串我想得到结果
eat today, eat tomorrow, drink today, drink tomorrow,
我必须做什么?我尝试使用拆分,但结果不太好。谢谢。
解决方案
一种方法是利用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.
[编辑] 第一个回复发表时,我正在写我的回复。随意删除这个。[/编辑]
推荐阅读
- sql - 如何将条件查询放在游标内?
- vb.net - VB.net 登录 访问级别 MS 访问
- security - 我们可以限制安全通道协议 (SCP) 02 通信中的“安全级别”吗?
- pandas - 如何从熊猫的列中获取组的组合
- sass - ionic3 中 Android 设备上的一个恼人的小方块?
- python - 如何在没有标识符的表中查找值?(Python,硒)
- php - woocommerce_cart_updated 挂钩未按预期工作 - WooCommerce
- ios - iOS 上的 UITextField 验证有什么更好的方法?
- pixi.js - 如何在pixijs中渲染一个圆圈
- java - 由于 XQuery 持续时间长而导致的内部服务器错误 (MarkLogic)