You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何用单行代码实现下划线分隔字符串拆分拼接为累积前缀数组?

解决方案

Python 版本

单行代码如下:

res = ['_'.join("1_2_3_4_5".split('_')[:i+1]) for i in range(len("1_2_3_4_5".split('_')))]

把代码中的硬编码字符串替换为你自己的变量即可,输出结果为['1', '1_2', '1_2_3', '1_2_3_4', '1_2_3_4_5'],完全匹配需求。

JavaScript 版本

单行代码如下:

const res = "1_2_3_4_5".split('_').map((_, idx, arr) => arr.slice(0, idx + 1).join('_'));

PHP 版本

单行代码如下:

$res = array_map(fn($i) => implode('_', array_slice(explode('_', '1_2_3_4_5'), 0, $i + 1)), range(0, count(explode('_', '1_2_3_4_5')) - 1));

内容的提问来源于stack exchange,提问作者do1emu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:09:03