如果你真的想使用正则表达式(如果你真的确定你的弦总是被这样的格式可能是OK),那这样的事情,你的情况:
$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>
- 然后任意n
:空格
- 然后
<td>
- 那么你想要什么捕捉
- 然后
</td>
- ,并再次同
- 最后,
</tr>
,而且我用赭
?
in th Ë正则表达式来在非贪婪模式匹配
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,计数必须至少为1,... )
作为便笺:使用正则表达式来解析HTML一般不是一个好主意;如果你可以使用一个真正的解析器,它应该是更安全的方式...
可能重复与正则表达式?](http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-一,雷杰) – 2011-07-09 21:01:07