Reputation: 23989
I am using the following to parse an html page and return the images:
$html = file_get_html($url);
foreach($html->find('img') as $e){
$image = $e->src;
}
Ideally though I only want to show files with .jpg extension - I know I can probably use preg_match but is there a more efficient way?
Upvotes: 0
Views: 123
Reputation: 88657
pathinfo()
is the native PHP function you are looking for. Yes you can manipulate the string however you want, but if you are looking for the "right" way to do it then here it is:
$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
}
}
Upvotes: 3
Reputation: 95121
Your code is fine. This would work for your case
// 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>';
}
Upvotes: 3
Reputation: 3428
$split = explode(".", $image);
$extention = $split[count($split)-1];
Upvotes: 0