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
相关产品推荐
相关产品推荐

