Vin*_* V. 0 html php regex html-parsing
我正在尝试制作一个正则表达式来从表中取出一些数据。
我现在得到的代码是:
<table>
<tr>
<td>quote1</td>
<td>have you trying it off and on again ?</td>
</tr>
<tr>
<td>quote65</td>
<td>You wouldn't steal a helmet of a policeman</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
这我想替换为:
quote1:你有没有反复尝试过?
quote65:你不会偷警察的头盔
我已经写的代码是这样的:
%<td>((?s).*?)</td>%
Run Code Online (Sandbox Code Playgroud)
但现在我被困住了。
如果你真的想使用正则表达式(如果你真的很确定你的字符串总是这样格式化可能没问题),那么像这样的东西,在你的情况下:
$str = <<<A
<table>
<tr>
<td>quote1</td>
<td>have you trying it off and on again ?</td>
</tr>
<tr>
<td>quote65</td>
<td>You wouldn't steal a helmet of a policeman</td>
</tr>
</table>
A;
$matches = array();
preg_match_all('#<tr>\s+?<td>(.*?)</td>\s+?<td>(.*?)</td>\s+?</tr>#', $str, $matches);
var_dump($matches);
Run Code Online (Sandbox Code Playgroud)
关于正则表达式的几句话:
<tr>
<td>
</td>
</tr>
我使用:
?
在正则表达式中以非贪婪模式匹配preg_match_all
获取所有匹配项然后你会得到你想要的结果$matches[1]
and $matches[2]
(not $matches[0]
) ; 这是var_dump
我使用的输出(我删除了条目 0,以使其更短):
array
0 =>
...
1 =>
array
0 => string 'quote1' (length=6)
1 => string 'quote65' (length=7)
2 =>
array
0 => string 'have you trying it off and on again ?' (length=37)
1 => string 'You wouldn't steal a helmet of a policeman' (length=42)
Run Code Online (Sandbox Code Playgroud)
然后你只需要操作这个数组,用一些字符串连接等;例如,像这样:
$num = count($matches[1]);
for ($i=0 ; $i<$num ; $i++) {
echo $matches[1][$i] . ':' . $matches[2][$i] . '<br />';
}
Run Code Online (Sandbox Code Playgroud)
你得到:
quote1:have you trying it off and on again ?
quote65:You wouldn't steal a helmet of a policeman
Run Code Online (Sandbox Code Playgroud)
注意:您应该添加一些安全检查(例如preg_match_all
必须返回 true,计数必须至少为 1,...)
附带说明:使用正则表达式解析 HTML 通常不是一个好主意;如果你可以使用真正的解析器,它应该更安全......