161

私のウェブサイトにあるすべての画像がタイトルと代替表現とともにリストされているページを作成したいと思います。

すべての HTML ファイルを検索してロードするための小さなプログラムを既に作成しましたが、この HTML から を抽出する方法に行き詰まってsrcいますtitlealt

<img src="/image/fluffybunny.jpg" title="Harvey the bunny" alt="a cute little fluffy bunny" />

これはいくつかの正規表現で行う必要があると思いますが、タグの順序が異なる可能性があり、すべてのタグが必要なため、これをエレガントな方法で解析する方法がよくわかりません (ハード文字で実行できますチャーウェイですが、それは痛いです)。

4

10 に答える 10

265
$url="http://example.com";

$html = file_get_contents($url);

$doc = new DOMDocument();
@$doc->loadHTML($html);

$tags = $doc->getElementsByTagName('img');

foreach ($tags as $tag) {
       echo $tag->getAttribute('src');
}
于 2010-05-30T05:43:50.690 に答える
214

編集:今、私はよく知っています

この種の問題を解決するために regexp を使用することは悪い考えであり、メンテナンスや信頼性の低いコードにつながる可能性があります。HTML パーサーを使用することをお勧めします。

正規表現を使用したソリューション

その場合、プロセスを 2 つの部分に分割することをお勧めします。

  • すべての img タグを取得する
  • メタデータを抽出する

ドキュメントが xHTML に厳密ではないため、XML パーサーを使用できないと仮定します。この Web ページのソース コードを使用した EG :

/* preg_match_all match the regexp in all the $html string and output everything as 
an array in $result. "i" option is used to make it case insensitive */

preg_match_all('/<img[^>]+>/i',$html, $result); 

print_r($result);
Array
(
    [0] => Array
        (
            [0] => <img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" />
            [1] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />
            [2] => <img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" />
            [3] => <img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" />
            [4] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />

[...]
        )

)

次に、ループを使用してすべての img タグ属性を取得します。

$img = array();
foreach( $result as $img_tag)
{
    preg_match_all('/(alt|title|src)=("[^"]*")/i',$img_tag, $img[$img_tag]);
}

print_r($img);

Array
(
    [<img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" />] => Array
        (
            [0] => Array
                (
                    [0] => src="/Content/Img/stackoverflow-logo-250.png"
                    [1] => alt="logo link to homepage"
                )

            [1] => Array
                (
                    [0] => src
                    [1] => alt
                )

            [2] => Array
                (
                    [0] => "/Content/Img/stackoverflow-logo-250.png"
                    [1] => "logo link to homepage"
                )

        )

    [<img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />] => Array
        (
            [0] => Array
                (
                    [0] => src="/content/img/vote-arrow-up.png"
                    [1] => alt="vote up"
                    [2] => title="This was helpful (click again to undo)"
                )

            [1] => Array
                (
                    [0] => src
                    [1] => alt
                    [2] => title
                )

            [2] => Array
                (
                    [0] => "/content/img/vote-arrow-up.png"
                    [1] => "vote up"
                    [2] => "This was helpful (click again to undo)"
                )

        )

    [<img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" />] => Array
        (
            [0] => Array
                (
                    [0] => src="/content/img/vote-arrow-down.png"
                    [1] => alt="vote down"
                    [2] => title="This was not helpful (click again to undo)"
                )

            [1] => Array
                (
                    [0] => src
                    [1] => alt
                    [2] => title
                )

            [2] => Array
                (
                    [0] => "/content/img/vote-arrow-down.png"
                    [1] => "vote down"
                    [2] => "This was not helpful (click again to undo)"
                )

        )

    [<img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" />] => Array
        (
            [0] => Array
                (
                    [0] => src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG"
                    [1] => alt="gravatar image"
                )

            [1] => Array
                (
                    [0] => src
                    [1] => alt
                )

            [2] => Array
                (
                    [0] => "http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG"
                    [1] => "gravatar image"
                )

        )

   [..]
        )

)

正規表現は CPU を集中的に使用するため、このページをキャッシュすることをお勧めします。キャッシュ システムがない場合は、ob_startを使用してテキスト ファイルから読み込み/保存することで、独自のシステムを微調整できます。

これはどのように機能しますか?

まず、パターンに一致するすべての文字列を取得し、それを 3 番目のパラメーターに出力する関数であるpreg_ match_ allを使用します。

正規表現:

<img[^>]+>

すべての html Web ページに適用します。" " で始まり、">" 以外の文字を含み、 > で終わるすべての文字列<imgとして読み取ることができます。

(alt|title|src)=("[^"]*")

各 img タグに連続して適用します。これは、「alt」、「title」、または「src」で始まり、「=」、「"」、「"」ではなく「"」で終わるすべての文字列として読み取ることができます。 () の間の部分文字列を分離します

最後に、正規表現を扱いたいときはいつでも、すぐにテストできる優れたツールがあると便利です。このオンライン正規表現テスターを確認してください。

編集:最初のコメントへの回答。

一重引用符を使用している (願わくば少数の) 人々について考えていなかったのは事実です。

' だけを使用する場合は、すべての " を ' に置き換えてください。

両方混ぜれば。まず、自分自身を平手打ちする必要があります :-) 代わりに ("|') を使用するか、" と [^ø] を使用して [^"] を置き換えます。

于 2008-09-27T11:33:36.887 に答える
67

タスクに PHP の XML 機能を使用する小さな例を挙げると、次のようになります。

$doc=new DOMDocument();
$doc->loadHTML("<html><body>Test<br><img src=\"myimage.jpg\" title=\"title\" alt=\"alt\"></body></html>");
$xml=simplexml_import_dom($doc); // just to make xpath more simple
$images=$xml->xpath('//img');
foreach ($images as $img) {
    echo $img['src'] . ' ' . $img['alt'] . ' ' . $img['title'];
}

DOMDocument::loadHTML()このメソッドは HTML 構文に対応でき、入力ドキュメントを XHTML にする必要がないため、このメソッドを使用しました。厳密に言えば、a への変換SimpleXMLElementは必要ありません。xpath の使用と xpath の結果がより簡単になるだけです。

于 2008-09-26T10:18:20.393 に答える
9

XHTML の場合、たとえば、simpleXML のみが必要です。

<?php
$input = '<img src="/image/fluffybunny.jpg" title="Harvey the bunny" alt="a cute little fluffy bunny"/>';
$sx = simplexml_load_string($input);
var_dump($sx);
?>

出力:

object(SimpleXMLElement)#1 (1) {
  ["@attributes"]=>
  array(3) {
    ["src"]=>
    string(22) "/image/fluffybunny.jpg"
    ["title"]=>
    string(16) "Harvey the bunny"
    ["alt"]=>
    string(26) "a cute little fluffy bunny"
  }
}
于 2008-09-26T10:30:44.793 に答える
6

preg_match を使用してそれを行いました。

私の場合、<img>Wordpress から取得した 1 つのタグ (および他のマークアップを含まない) を含む文字列がありsrc、timthumb を介して実行できるように属性を取得しようとしていました。

// get the featured image
$image = get_the_post_thumbnail($photos[$i]->ID);

// get the src for that image
$pattern = '/src="([^"]*)"/';
preg_match($pattern, $image, $matches);
$src = $matches[1];
unset($matches);

タイトルまたは alt を取得するパターンでは、単純に を使用$pattern = '/title="([^"]*)"/';してタイトルまたは$pattern = '/title="([^"]*)"/';alt を取得できます。残念ながら、私の正規表現は 1 回のパスで 3 つすべて (alt/title/src) を取得するには不十分です。

于 2010-09-28T16:59:34.353 に答える
5

simplehtmldomを使用できます。jQuery セレクターのほとんどは、simplehtmldom でサポートされています。例を以下に示します

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
       echo $element->src . '<br>';

// Find all links
foreach($html->find('a') as $element)
       echo $element->href . '<br>'; 
于 2014-01-27T07:24:20.060 に答える
4

スクリプトは次のように編集する必要があります

foreach( $result[0] as $img_tag)

preg_match_allは配列の配列を返すため

于 2009-09-27T05:14:26.607 に答える
1

これは、同様の目的で上記のすべての情報からまとめた PHP 関数です。つまり、画像タグの幅と長さのプロパティをオンザフライで調整します...おそらく少し不格好ですが、確実に動作するようです:

function ReSizeImagesInHTML($HTMLContent,$MaximumWidth,$MaximumHeight) {

// find image tags
preg_match_all('/<img[^>]+>/i',$HTMLContent, $rawimagearray,PREG_SET_ORDER); 

// put image tags in a simpler array
$imagearray = array();
for ($i = 0; $i < count($rawimagearray); $i++) {
    array_push($imagearray, $rawimagearray[$i][0]);
}

// put image attributes in another array
$imageinfo = array();
foreach($imagearray as $img_tag) {

    preg_match_all('/(src|width|height)=("[^"]*")/i',$img_tag, $imageinfo[$img_tag]);
}

// combine everything into one array
$AllImageInfo = array();
foreach($imagearray as $img_tag) {

    $ImageSource = str_replace('"', '', $imageinfo[$img_tag][2][0]);
    $OrignialWidth = str_replace('"', '', $imageinfo[$img_tag][2][1]);
    $OrignialHeight = str_replace('"', '', $imageinfo[$img_tag][2][2]);

    $NewWidth = $OrignialWidth; 
    $NewHeight = $OrignialHeight;
    $AdjustDimensions = "F";

    if($OrignialWidth > $MaximumWidth) { 
        $diff = $OrignialWidth-$MaximumHeight; 
        $percnt_reduced = (($diff/$OrignialWidth)*100); 
        $NewHeight = floor($OrignialHeight-(($percnt_reduced*$OrignialHeight)/100)); 
        $NewWidth = floor($OrignialWidth-$diff); 
        $AdjustDimensions = "T";
    }

    if($OrignialHeight > $MaximumHeight) { 
        $diff = $OrignialHeight-$MaximumWidth; 
        $percnt_reduced = (($diff/$OrignialHeight)*100); 
        $NewWidth = floor($OrignialWidth-(($percnt_reduced*$OrignialWidth)/100)); 
        $NewHeight= floor($OrignialHeight-$diff); 
        $AdjustDimensions = "T";
    } 

    $thisImageInfo = array('OriginalImageTag' => $img_tag , 'ImageSource' => $ImageSource , 'OrignialWidth' => $OrignialWidth , 'OrignialHeight' => $OrignialHeight , 'NewWidth' => $NewWidth , 'NewHeight' => $NewHeight, 'AdjustDimensions' => $AdjustDimensions);
    array_push($AllImageInfo, $thisImageInfo);
}

// build array of before and after tags
$ImageBeforeAndAfter = array();
for ($i = 0; $i < count($AllImageInfo); $i++) {

    if($AllImageInfo[$i]['AdjustDimensions'] == "T") {
        $NewImageTag = str_ireplace('width="' . $AllImageInfo[$i]['OrignialWidth'] . '"', 'width="' . $AllImageInfo[$i]['NewWidth'] . '"', $AllImageInfo[$i]['OriginalImageTag']);
        $NewImageTag = str_ireplace('height="' . $AllImageInfo[$i]['OrignialHeight'] . '"', 'height="' . $AllImageInfo[$i]['NewHeight'] . '"', $NewImageTag);

        $thisImageBeforeAndAfter = array('OriginalImageTag' => $AllImageInfo[$i]['OriginalImageTag'] , 'NewImageTag' => $NewImageTag);
        array_push($ImageBeforeAndAfter, $thisImageBeforeAndAfter);
    }
}

// execute search and replace
for ($i = 0; $i < count($ImageBeforeAndAfter); $i++) {
    $HTMLContent = str_ireplace($ImageBeforeAndAfter[$i]['OriginalImageTag'],$ImageBeforeAndAfter[$i]['NewImageTag'], $HTMLContent);
}

return $HTMLContent;

}
于 2011-11-09T07:44:52.330 に答える
-1

PHPでの解決策は次のとおりです。

QueryPathをダウンロードして、次のようにします。

$doc= qp($myHtmlDoc);

foreach($doc->xpath('//img') as $img) {

   $src= $img->attr('src');
   $title= $img->attr('title');
   $alt= $img->attr('alt');

}

これで完了です。

于 2010-11-13T13:52:25.357 に答える