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

PHP如何按每两次分隔符出现规则将字符串拆分为键值对数组

实现每两次/-/分隔符拆分生成键值对数组的方案

直接使用以下代码即可实现需求:

<?php
$measurements = 'Hauteur/-/175 cm/-/Height/-/5\'9\'\'/-/00010/--/Buste (Femme)/-/92 cm/-/Bust (Women)/-/36\'\'/-/00020/--/Taille/-/74 cm/-/Waist/-/29\'\'/-/00022/--/Hanches/-/99 cm/-/Hips/-/39\'\'/-/00023';

// 拆分原始字符串
$rawArr = explode("/-/", $measurements);
$result = [];
$tempKey = '';

foreach ($rawArr as $item) {
    // 过滤无效项:原/--分隔残留的含/的项、纯数字的ID项
    if (str_contains($item, '/') || ctype_digit(trim($item, '-'))) {
        continue;
    }
    // 按顺序两两配对为键值对
    if (empty($tempKey)) {
        $tempKey = $item;
    } else {
        $result[$tempKey] = $item;
        $tempKey = '';
    }
}

// 输出结果
print_r($result);
?>

兼容性说明

如果使用PHP8以下版本,将过滤条件中的str_contains($item, '/')替换为strpos($item, '/') !== false即可正常运行。

输出结果

运行上述代码会得到你需要的键值对数组:

Array
(
    [Hauteur] => 175 cm
    [Height] => 5'9''
    [Buste (Femme)] => 92 cm
    [Bust (Women)] => 36''
    [Taille] => 74 cm
    [Waist] => 29''
    [Hanches] => 99 cm
    [Hips] => 39''
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:51:01