仅获取缺少 alt 属性的图像链接,并在 PHP 中preg_match_all


Get only images links that missing the alt attribute with preg_match_all in PHP

你好,对不起我的英语不好。

我正在尝试从第三方网站获取所有图像链接,但我只想获取没有alt属性的链接。我想输出链接。

现在我有这个代码:

<?php
$content = file_get_contents('domain.com');
preg_match_all('/<img(.*?)>/is',$content,$page_images);
$total_images = count($page_images[1]);
preg_match_all('/<img(.*?)alt="(.*?)"(.*?)>/is',$content,$alt_images);
$total_alt = count($alt_images[2]);
$missing_alt = $total_images - $total_alt; 

echo $missing_alt.' alt attributes are empty or missing';
?>

此代码正常工作,并提供缺少 alt 属性的图像总数。

现在我还想输出缺少 alt=" 属性的链接。

HTML

不应该用正则表达式解析。

使用DOMDocument或SimpleHTMLParser更好,更安全,更容易。