用于包装所有 tr 的正则表达式包含 thead 中的 th 标签

Regular expression for wraping all tr contains th tags in thead

我的正则表达式有问题,我需要包装所有包含 thtr 并将其放在 thead 中。我有一个变量 $html,其中包含一个 html table,如下所示:

$html ="
<table>
<tr>
  <th>header1</th> 
  <th>header2</th>
  <th>header3</th>
</tr>
<tr>
  <th>header21</th> 
  <th>header22</th>
  <th>header23</th>
</tr>

<tr>
  <td>body1</td> 
  <td>body2</td>
  <td>body3</td>
</tr>
<tr>
  <td>body21</td> 
  <td>body22</td>
  <td>body23</td>
</tr>
</table>";

我写的正则表达式是这样的

$html = preg_replace_callback(
'#(<tr.*?<th>.*?<th>.*?<\/tr>)#s', 
 function($match) {
        return '<thead>' . $match[0] . '</thead>';
    },
 $html);

但是我得到的结果和我想要的不一样。 现在,我将 tr 变成不同的 thead

尝试用正则表达式解析HTML不是一个好主意。

就是说,你需要去掉一个问号,这给你无限但尽可能少。对于第一个和最后一个 <th> 之间的 space,您希望它尽可能多。这将达到目的:

              #this is supposed to be as greedy as possible
              #
~(<tr.*?<th>.*<th>.*?</tr>)~s

https://regex101.com/r/fR1xB5/1

如果页面中有两个table,最好尝试下面一个。

   (<tr>\s*(<th>((?!<tr>).)*</th>)+\s*</tr>)

示例:https://regex101.com/r/fR1xB5/2