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

PHP如何使用正则表达式匹配提取字符串中括号包裹的数字内容

PHP匹配括号包裹数字的正则实现

核心正则

根据需求分两种常用场景对应正则:

  • 匹配完整的(数字)片段:/\(\d+\)/
  • 仅提取括号内的数字内容(带捕获组):/\((\d+)\)/

正则说明

  • /:PHP正则要求的边界分隔符
  • \(:转义匹配左半角小括号(,避免被识别为正则元字符
  • \d+:匹配1位及以上的阿拉伯数字
  • \):转义匹配右半角小括号)
  • 捕获组(\d+):将括号内的数字单独存入匹配结果的捕获分组,无需后续额外处理去除括号

PHP使用示例

// 待匹配的示例字符串
$testStr = 'Lorem Ipsum is simply dummy text (100) of the printing and typesetting industry. Lorem Ipsum has been the (2000) industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to (40) make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularized in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.';

// 场景1:获取带括号的匹配结果
preg_match_all('/\(\d+\)/', $testStr, $resultWithBracket);
// 输出结果:Array ( [0] => Array ( [0] => (100) [1] => (2000) [2] => (40) ) )

// 场景2:直接获取括号内的数字
preg_match_all('/\((\d+)\)/', $testStr, $resultOnlyNumber);
// 输出结果:Array ( [0] => Array ( [0] => (100) [1] => (2000) [2] => (40) ) [1] => Array ( [0] => 100 [1] => 2000 [2] => 40 ) )

拓展说明

如果需要匹配带小数的数字,可将正则中的\d+替换为\d+(?:\.\d+)?,即可匹配类似(123.45)的格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:48:00