如何用正则表达式嵌套分组提取 table 中的 td ?

问题描述

想通过正则匹配 table 中的 td ,以下是我的代码思路。想问一下如何一个正则就可以得出我想要的结果。或则正则就不支持这种情况的分组?我找了一圈都没有找到想要的答案。请各位老司机指点一二,给个思路也行

$matches = [];
$str = '<table><tr><td>111</td><td>111</td><td>111</td></tr><tr><td>222</td><td>222</td><td>222</td></tr></table>';

## 本来想通过一个正则得出结果
preg_match_all('$(?:<tr>.*?(?:<td>(.*?)</td>).*?</tr>)$', $str, $matches);
dd($matches);

## 这个是目前临时使用的方法
preg_match_all('$(?P<row><tr>.*?</tr>)$', $str, $matches);
array_walk($matches[1], function (&$item){
  $matches = [];
  preg_match_all('$<td>(?P<col>.*?)</td>$', $item, $matches);
  $item = $matches['col'];
});
dd($matches);

期望得到的结果

 array:2 [
    0 => array:3 [
      0 => "111"
      1 => "111"
      2 => "111"
    ]
    1 => array:3 [
      0 => "222"
      1 => "222"
      2 => "222"
    ]
  ]

实际得到的结果

array:2 [
  0 => array:2 [
    0 => "<tr><td>111</td><td>111</td><td>111</td></tr>"
    1 => "<tr><td>222</td><td>222</td><td>222</td></tr>"
  ]
  1 => array:2 [
    0 => "111"
    1 => "222"
  ]
]
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 4
诺墨

这种情况最简单就是直接用 DOM 解析库 代替正则。

github.com/sunra/php-simple-html-d... 就可以很快给到你答案。

3年前 评论
少林驻武当办事处王喇嘛 (楼主) 3年前

第二种方法不是挺好的吗?

3年前 评论
少林驻武当办事处王喇嘛 (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!