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

如何使用preg_match匹配URL中所有被%2C分隔的正整数?

问题根因
  • 当前使用的preg_match()函数仅会返回第一个匹配到的结果,无法捕获所有符合规则的数字
  • 直接全局匹配全URL的数字存在误匹配风险:若URL其他路径段、域名中存在数字,会被错误提取到结果中
实现方案

方案1:先定位目标片段再拆分(推荐,准确率更高)

先提取/blah/后面的内容,解码后拆分得到数组,适配无数字、任意数量数字的场景:

$url = "https://test.example.com/blah/12345%2C80%2C8263473%2C9475834343";
$prefix = 'https://test.example.com/blah/';
$result = [];

// 校验URL前缀匹配
if (str_starts_with($url, $prefix)) {
    // 提取前缀后的数字片段
    $numSegment = substr($url, strlen($prefix));
    // 解码URL编码的逗号
    $decodedSegment = urldecode($numSegment);
    // 按逗号拆分、过滤空值、转整数
    $result = array_map('intval', array_filter(explode(',', $decodedSegment)));
}

print_r($result);

运行输出为:

Array
(
    [0] => 12345
    [1] => 80
    [2] => 8263473
    [3] => 9475834343
)

如果/blah/后无数字,会直接返回空数组,符合需求。如果前缀不固定,可以先用parse_url($url, PHP_URL_PATH)拿到URL路径,再提取路径中/blah/后的片段即可。

方案2:正则全局匹配

如果要直接通过正则实现,将preg_match替换为支持全局匹配的preg_match_all,调整正则规则限定匹配/blah/后的数字即可:

$url = "https://test.example.com/blah/12345%2C80%2C8263473%2C9475834343";
preg_match_all('#/blah/(?:%2C)*(\d+)#', $url, $matches);
$result = array_map('intval', $matches[1]);

print_r($result);

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

相关产品推荐
方舟 Agent Plan

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

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