我有一个regex的问题,我需要包装所有包含th
的tr
,并将其放在thead
中。我有一个变量$html
,其中包含一个html表,如下所示:
$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>
之间的空间,您希望它尽可能多。这将是伎俩:
#this is supposed to be as greedy as possible
#
~(<tr.*?<th>.*<th>.*?</tr>)~s
见https://regex101.com/r/fR1xB5/1
如果页面中有两个表,最好是下面一个
(<tr>'s*(<th>((?!<tr>).)*</th>)+'s*</tr>)
示例:https://regex101.com/r/fR1xB5/2