如何用正则表达式嵌套分组提取 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"
]
]
推荐文章: