あなたはこれに慣れてDOMDocument
いないので、必要なものを抽出するために として知られる PHP の HTML パーサーを使用できることを説明します。正規表現は、HTML の解析に関して本質的にエラーが発生しやすく、多くの誤検出を引き起こしやすいため、使用しないでください。
まず、HTML があるとします。
$html = '<a href="http://www.mydomain.com/galeria/thumbnails.php?album=774" target="_blank"><img alt="/" src="http://img255.imageshack.us/img00/000/000001.png" height="133" width="113"></a>';
そして、それを DOMDocument にロードします。
$doc = new DOMDocument;
$doc->loadHTML( $html);
これで、HTML が読み込まれました。必要な要素を見つけます。ドキュメント内で他のタグに遭遇する可能性があると仮定して、直接タグを子として持つタグ<a>
を見つけたいとします。次に、正しいノードがあることを確認します。正しい情報を抽出する必要があります。それでは、それを見てみましょう:<a>
<img>
$results = array();
// Loop over all of the <a> tags in the document
foreach( $doc->getElementsByTagName( 'a') as $a) {
// If there are no children, continue on
if( !$a->hasChildNodes()) continue;
// Find the child <img> tag, if it exists
foreach( $a->childNodes as $child) {
if( $child->nodeType == XML_ELEMENT_NODE && $child->tagName == 'img') {
// Now we have the <a> tag in $a and the <img> tag in $child
// Get the information we need:
parse_str( parse_url( $a->getAttribute('href'), PHP_URL_QUERY), $a_params);
$results[] = array( $a_params['album'], $child->getAttribute('src'));
}
}
}
Aprint_r( $results);
は次のようになります。
Array
(
[0] => Array
(
[0] => 774
[1] => http://img255.imageshack.us/img00/000/000001.png
)
)
これは基本的なエラーチェックを省略していることに注意してください。追加できることの 1 つは内部ループにあります。次のように、の属性からパラメーターforeach
を正常に解析したことを確認できます。album
<a>
href
if( isset( $a_params['album'])) {
$results[] = array( $a_params['album'], $child->getAttribute('src'));
}
これで使用したすべての関数は、PHP ドキュメントにあります。