0

以下を使用して、html ページを解析し、画像を返します。

$html = file_get_html($url);

foreach($html->find('img') as $e){ 

    $image = $e->src;

            }

理想的には、拡張子が .jpg のファイルのみを表示したいのですが、おそらく preg_match を使用できることはわかっていますが、より効率的な方法はありますか?

4

3 に答える 3

3

注: ファイルに JPEG のような拡張子が付いているからといって、参照されているファイルの内容が実際に JPEG データであるとは限りません。


pathinfo()探しているネイティブ PHP 関数です。はい、必要に応じて文字列を操作できますが、「正しい」方法を探している場合は、次のとおりです。

$html = file_get_html($url);

// file extensions we are looking for
$allowedExtensions = ['jpg', 'jpeg', 'jpe'];

foreach($html->find('img') as $el){ 
    // file extensions are usually treated as case insensitive, but the
    // implied comparison operator used with in_array() is case sensitive
    // so normalise the data to lower-case.
    $extension = strtolower(pathinfo($el->src, PATHINFO_EXTENSION));

    if (in_array($extension, $allowedExtensions)) {
        // File has a JPEG-like file extension
    }
}
于 2012-04-04T12:04:30.723 に答える
3

あなたのコードは問題ありません。これはあなたのケースでうまくいくでしょう

// Create DOM from URL or file
$html = file_get_html('http://www.yahoo.com/');
// Find all images
foreach($html->find('img') as $element)
{
    $img = strtolower($element->src);
    if(pathinfo($img,PATHINFO_EXTENSION) == "jpg")
        echo $element->src . '<br>';
}
于 2012-04-04T12:11:28.163 に答える
0
$split = explode(".", $image);
$extention = $split[count($split)-1];
于 2012-04-04T12:03:49.080 に答える