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

在preg_match_all()正则中用#提取数据失败,求排查解决

正则表达式提取值失败问题解决

初始可正常匹配的代码:

$html = '<html><div data-id="ABC012" data-index="123" ...';
preg_match_all('/<div data-id="[A-Z\d]+" data-index="\d+"/', $html, $result);
var_dump($result);

修改后输出空数组的核心问题是:你在正则表达式里错误添加了不存在的#符号,原HTML字符串中data-id和data-index的属性值前并没有#,导致正则无法匹配到任何内容。

仅修正当前代码使其正常运行(不优化正则其他部分),只需移除正则里的两个#即可,正确代码如下:

$html = '<html><div data-id="ABC012" data-index="123" ...';
preg_match_all('/<div data-id="([A-Z\d]+)" data-index="(\d+)"/', $html, $result);
var_dump($result);

运行后$result数组中:

  • 索引0存储完整的匹配字符串
  • 索引1存储所有提取到的data-id值
  • 索引2存储所有提取到的data-index值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:10:19