本当に正規表現を使用したい場合 (文字列が常にそのようにフォーマットされることが本当に確実な場合は問題ないかもしれません)、あなたの場合、次のようなものはどうですか:
$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]
次に、 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)
次に、いくつかの文字列連結などを使用して、この配列を操作するだけです。たとえば、次のように:
$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 を解析することは、一般的にあまり良い考えではありません。本物のパーサーを使えば、もっと安全なはずです...