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

如何使用PHP拆分字符串中MB、GB单位的文件大小数据并提取数值

解决方案

问题原因

你之前substr判断失败的核心原因是你在处理file_size的时候额外拼接了一个空格在末尾:$file_size_ext = str_replace(' ', '',$data['file_size'])." ";,这会导致你取后缀的时候最后一位是空格,自然匹配不到GB/MB。

实现代码

场景1:处理你给出的长文本字符串

<?php
$data = "899.3MB 976.4MB 874.7MB 985.6MB 1.2GB 691.3MB 1.4GB 975.4MB 1.0GB 712.8MB 879.8MB 908.6MB 912.1MB 887.5MB 950.4MB 1.4GB 749.9MB 851.2MB 750.8MB 813.7MB 1.2GB 700MB 998.5MB 1010.8MB 989.7MB 1.1GB 797.5MB 699.5MB 683.7MB 1.0GB 958.2MB 1.1GB 1.0GB 1.0GB 1.0GB 1.1GB 1.0GB 1.0GB 846MB 873MB 753MB 1.1GB 970MB 749.9MB 750MB 650MB 845MB 1.1GB 1.3GB 1.2GB 1.1GB 867MB 940MB 946MB 909MB 909MB 913MB 893MB 892MB 889MB 730MB 848MB 855MB 1.15GB 853MB 765MB 1.2GB 863MB 838MB 753MB 960MB 868MB 967MB 1.06GB 751MB 1GB 1.2GB 920MB 1.2GB 897MB 1009.15MB 764MB 694MB 967MB 989.9MB 898MB 938MB 879.76MB 879.76MB 999.78MB 1.3GB 1.1GB 1.09GB";

$mb = [];
$gb = [];

// 按空格拆分所有大小项
$sizeItems = explode(' ', $data);
foreach ($sizeItems as $item) {
    $item = trim($item);
    if (empty($item)) continue;

    // 兼容PHP7及以下版本的后缀判断
    $suffix = substr($item, -2);
    $value = (float)substr($item, 0, -2);

    if (strtoupper($suffix) === 'GB') {
        $gb[] = $value;
    } elseif (strtoupper($suffix) === 'MB') {
        $mb[] = $value;
    }
}

// 求和直接用内置函数即可
$totalMb = array_sum($mb);
$totalGb = array_sum($gb);
?>

场景2:整合到你的MySQL查询逻辑

<?php
// 先初始化存储数组
$mb = [];
$gb = [];

while ($data = mysqli_fetch_array($records))
{
    $fileSize = trim($data['file_size']);
    if (empty($fileSize)) continue;

    $suffix = substr($fileSize, -2);
    $value = (float)substr($fileSize, 0, -2);

    if (strtoupper($suffix) === 'GB') {
        $gb[] = $value;
    } elseif (strtoupper($suffix) === 'MB') {
        $mb[] = $value;
    }
}
mysqli_close($db);

// 后续按需使用数组或者求和
$totalMb = array_sum($mb);
$totalGb = array_sum($gb);
?>

补充说明

  • 如果你用的是PHP8及以上版本,可以用更直观的str_ends_with($item, 'GB')来做后缀判断,不需要手动截取
  • 代码里加了strtoupper兼容小写的mb/gb后缀场景,如果你的数据确定都是大写可以去掉
  • 提取数值的时候直接转成float类型,不管是整数还是小数都能正常处理,求和不会有精度问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:48:03