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

如何从含短横线的字符串提取数字?如何拆分斜杠分隔数字串为变量

从包含短横线的字符串中提取数字

可以通过正则表达式或字符串过滤实现,以下是PHP环境下的常见操作示例:

  • 提取所有连续数字片段:
$str = "order-2024-item-156";
preg_match_all('/\d+/', $str, $matches);
$numbers = $matches[0]; // 结果为 ['2024', '156']
  • 提取第一个数字片段:
$str = "user-987-profile";
preg_match('/\d+/', $str, $match);
$first_num = $match[0]; // 结果为 '987'
  • 移除所有短横线并合并为单个数字:
$str = "123-45-678";
$combined_num = (int)str_replace('-', '', $str); // 结果为 12345678
拆分"16/32/25"格式字符串并赋值给变量

在PHP中可以使用explode()配合列表赋值或解构赋值实现:

  • 基础字符串赋值:
$str = "16/32/25";
list($i, $b, $c) = explode('/', $str);
// 此时 $i = '16', $b = '32', $c = '25'
  • 直接转为整数类型:
$str = "16/32/25";
[$i, $b, $c] = array_map('intval', explode('/', $str));
// 此时 $i = 16, $b = 32, $c = 25(PHP 7.1+支持解构语法)

注:若使用PHP版本低于7.1,可继续使用list()语法替代解构赋值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:55:22