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

PHP中如何高效从含座机、分机的字符串中提取以Mobile:开头的手机号

实现方案

可以直接用正则匹配实现,比你现有的多次字符串切割的方案效率更高,代码也更简洁。

代码实现

$stringList = [
    "a" => "Phone: xxx-xxx-xxxx ext. 215",
    "b" => "Phone: xxx-xxx-xxxx Mobile: 9xx-xxx-x000",
    "c" => "Mobile: 9xx-xxx-x000 Phone: xxx-xxx-xxxx",
    "d" => "Phone: xxx-xxx-xxxx Mobile: 9xx-xxx-x000 ext. 215",
    "e" => "Mobile: 9xx-xxx-x000 Phone: xxx-xxx-xxxx ext. 215",
    "f" => "Phone: xxx-xxx-xxxx ext. 215 Mobile: 9xx-xxx-x000"
];

$stringOutput = [];
foreach ($stringList as $k => $s) {
    // 匹配带Mobile:前缀的完整内容
    if (preg_match('/Mobile:\s*[0-9x-]+/', $s, $matches)) {
        $stringOutput[$k] = trim($matches[0]);
    }

    // 如果你不需要保留Mobile:前缀,只要手机号本身,替换成下面的代码即可
    // if (preg_match('/Mobile:\s*([0-9x-]+)/', $s, $matches)) {
    //     $stringOutput[$k] = trim($matches[1]);
    // }
}

print_r($stringOutput);

正则规则说明

  • Mobile: 精准匹配手机号固定前缀
  • \s* 匹配前缀后可能存在的任意数量空格
  • [0-9x-]+ 匹配手机号主体(由数字、x、横杠组成的连续字符,遇到空格、Phone:、ext.这类不符合规则的字符就会自动停止匹配,完全覆盖你给出的所有场景)

输出结果

和你原有代码的输出完全一致:

Array
(
    [b] => Mobile: 9xx-xxx-x000
    [c] => Mobile: 9xx-xxx-x000
    [d] => Mobile: 9xx-xxx-x000
    [e] => Mobile: 9xx-xxx-x000
    [f] => Mobile: 9xx-xxx-x000
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 00:15:06