私はテキストを持っています
<div class="ti"><div class="pic">
<a href="/categories/rr/1.html"><img src="http://www.erty.com/images/440f2d2a.jpg" alt="Ind"> <span>Ind</span></a> (98)
</div></div><div class="ti"><div class="pic">
<a href="/categories/ert/1.html"><img src="http://www.erty.com/images/4123d2b.jpg" alt="Wes"> <span>Wes</span></a> (6044)
</div></div>
PHPでpreg_match_allを使用して取得する方法
/categories/rr/1.html
インド
98
すべてのエントリに対して。
私は試した
preg_match_all('|[^<div class="ti"><div class="pic">].*?[^<\/div><\/div>]+|',
$test_html,
$out, PREG_PATTERN_ORDER);
しかし、機能していません。
回答 3 件
それは正規表現の仕事ではありません。 PHPには、DOMを介してノードを照会できるHTMLファイルを解析するための組み込みクラスがあります。
$dom = new DOMDocument(); libxml_use_internal_errors(true); $dom->loadHTML($html); libxml_use_internal_errors(false); $xpath = new DOMXPath($dom); $pics = $xpath->query('//div[@class="ti"]/div[@class="pic"]'); $data = []; foreach ($pics as $pic) { $data[] =[ 'href' => $pic->getElementsByTagName('a')[0]->getAttribute('href'), 'src' => $pic->getElementsByTagName('img')[0]->getAttribute('src'), 'conetnt' => trim($pic->textContent) ]; } print_r($data);
出力:
Array ( [0] => Array ( [href] => /categories/rr/1.html [src] => http://www.erty.com/images/440f2d2a.jpg [conetnt] => Ind (98) ) [1] => Array ( [href] => /categories/ert/1.html [src] => http://www.erty.com/images/4123d2b.jpg [conetnt] => Wes (6044) ) )
$regex = '/href="(.*?)".*src="(.*?)".*alt="(.*?)".*\((\d+)\)/ms'; $string = ' <div class="ti"><div class="pic"> <a href="/categories/rr/1.html"><img src="http://www.erty.com/images/440f2d2a.jpg" alt="Ind"> <span>Ind</span></a> (98) </div></div><div class="ti"><div class="pic"> <a href="/categories/ert/1.html"><img src="http://www.erty.com/images/4123d2b.jpg" alt="Wes"> <span>Wes</span></a> (6044) </div></div> '; preg_match_all($regex, $string, $matches); print_r($matches);
出力:
Array ( [0] => Array ( [0] => href="/categories/rr/1.html"><img src="http://www.erty.com/images/440f2d2a.jpg" alt="Ind"> <span>Ind</span></a> (98) </div></div><div class="ti"><div class="pic"> <a href="/categories/ert/1.html"><img src="http://www.erty.com/images/4123d2b.jpg" alt="Wes"> <span>Wes</span></a> (6044) ) [1] => Array ( [0] => /categories/rr/1.html ) [2] => Array ( [0] => http://www.erty.com/images/4123d2b.jpg ) [3] => Array ( [0] => Wes ) [4] => Array ( [0] => 6044 ) )
関連した質問
- 正規表現で正しくフィルタリングする方法
- PHPの正規表現preg_replaceコマンドの置換パターンに。 '\ 1'を含める方法
- php:変数に特定の文字があるかどうかを確認する
- ネガティブルックアラウンドで定義されたルートは、ネガティブアサーションにもかかわらずルートと一致します
- PHP-内部コンテンツを含む完全なDivクラスを取得するための再帰正規表現
- PHPで正規表現が機能しないのはなぜですか?
- 特別な条件でのみ文字列から数字を削除する正規表現ガイド
- PHP:pregは最後の行を除くすべての文を分割します
- @言及のユーザー名のスペースとリンクの小文字
- PHPでコンテンツの一部を文字列に保持しながら、角かっこを置き換えるにはどうすればよいですか?
RegExpでHTMLを解析しようとしないでください。
htmlファイルはおそらくXMLファイルでもあるため、これを試してください。
または、Webサイトをスクレイピングする場合は、node.jsアプリでjQueryセレクターを使用することをお勧めします。