如果你真的想使用正则表达式(如果你真的确定你的字符串总是这样格式化可能没问题),在你的情况下这样的东西呢:
$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);
关于正则表达式的几句话:
<tr>
- 然后是任意数量的空格
- 然后
<td>
- 然后你想捕捉什么
- 然后
</td>
- 还是一样
- 最后,
</tr>
我使用:
-
正则表达式中的
? 在非贪婪模式下匹配
-
preg_match_all 获取所有匹配项
然后你在$matches[1]和$matches[2]中得到你想要的结果(不是$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)
然后你只需要操作这个数组,用一些字符串连接或类似的东西;例如,像这样:
$num = count($matches[1]);
for ($i=0 ; $i<$num ; $i++) {
echo $matches[1][$i] . ':' . $matches[2][$i] . '<br />';
}
你会得到:
quote1:have you trying it off and on again ?
quote65:You wouldn't steal a helmet of a policeman
注意:您应该添加一些安全检查(例如 preg_match_all 必须返回 true,count 必须至少为 1,...)
附带说明:使用正则表达式解析 HTML 通常不是一个好主意;如果你可以使用真正的解析器,它应该更安全......