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

如何用PHP正则从HTML字符串提取非零美元金额的<span>文本

问题解决:筛选指定美元金额

测试数据

>0 Dollar</span
>0.01 Dollar</span
>0.00 Dollar</span 
>50.00 Dollar</span

需求

保留除「0.00 Dollar」和「0 Dollar」之外的美元金额。

当前代码

$str = $table['contents'];
$pattern = "/(Need help here)/";    
$a = preg_match_all($pattern, $str, $matches);
print_r($matches);

期望输出

包含「0.01 Dollar」和「50.00 Dollar」的数组。

解决方案

使用带否定前瞻的正则表达式,精准排除不需要的金额格式,匹配目标内容:

正则表达式

>(?!(0\.00|0) Dollar)(\d+\.?\d* Dollar)</span

正则规则说明

  • >:匹配每行开头的大于号
  • (?!(0\.00|0) Dollar):否定前瞻断言,确保当前位置后不是「0.00 Dollar」或「0 Dollar」
  • (\d+\.?\d* Dollar):匹配合法金额格式,支持整数(如50)或小数(如0.01)形式的数字,后跟「 Dollar」
  • </span:匹配每行结尾的标签片段

修改后的代码

$str = $table['contents'];
$pattern = "/>(?!(0\.00|0) Dollar)(\d+\.?\d* Dollar)</span/";    
preg_match_all($pattern, $str, $matches);
// 提取第二个分组的结果,即为目标金额数组
print_r($matches[1]);

运行后输出的数组将包含「0.01 Dollar」和「50.00 Dollar」。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 00:20:56