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

PHP实现移除尺寸字符串中的0值及对应维度标识

解决方案

要同步处理尺寸值和对应的维度标识,不能只做简单的字符串替换,得把两部分拆分后对应筛选再重组。下面是可行的PHP实现:

$ship_weight_attr = "1 x 0 x 1 (L X W X H)"; // 示例输入

// 1. 拆分尺寸值和维度标识
preg_match('/^(.*?)\s*\((.*?)\)$/', $ship_weight_attr, $matches);
$sizePart = trim($matches[1] ?? '');
$dimPart = trim($matches[2] ?? '');

// 2. 分割成数组并去除元素前后空格
$sizes = array_map('trim', explode('x', $sizePart));
$dims = array_map('trim', explode('X', $dimPart));

// 3. 过滤掉值为0或空的项,同步保留对应维度
$filteredSizes = [];
$filteredDims = [];
foreach ($sizes as $index => $size) {
    if ($size !== '0' && $size !== '') {
        $filteredSizes[] = $size;
        $filteredDims[] = $dims[$index] ?? '';
    }
}

// 4. 重组最终字符串
$result = '';
if (!empty($filteredSizes)) {
    $result = implode(' x ', $filteredSizes) . ' (' . implode(' X ', $filteredDims) . ')';
}

echo $result; // 输出:1 x 1 (L X H)

逻辑说明

  • 用正则把括号前的尺寸值和括号内的维度标识拆分开,兼容内容前后可能存在的空格
  • 将尺寸、维度分别按分隔符分割为数组,同时清理每个元素的冗余空格
  • 遍历数组时,只保留尺寸值不为0且不为空的项,同步保留对应的维度标识
  • 最后把过滤后的数组重新拼接成符合要求的格式

测试不同场景

  • 输入1 x 1 x 0 (L X W X H) → 输出1 x 1 (L X W)
  • 输入1 x 1 x (L X W X H) → 输出1 x 1 (L X W)
  • 输入0 x 0 x 0 (L X W X H) → 输出空字符串(可根据需求调整默认显示内容)
  • 输入5 x (L X W X H) → 输出5 (L)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:15:31