如果你真的想使用正則表達式(如果你真的確定你的弦總是被這樣的格式可能是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