基本原理
- 使用
file_get_contents或curl获取网页内容。 - 解析网页内容,提取图片的
src属性。 - 将图片下载到本地。
使用file_get_contents与正则表达式
<?php
// 获取网页内容
$html = file_get_contents('https://www.example.com');
// 正则表达式匹配图片src
$pattern = '/<img.*?src="(.*?)".*?>/i';
preg_match_all($pattern, $html, $matches);
// 输出所有匹配的图片src
foreach ($matches[1] as $match) {
echo "图片路径:" . $match . "<br>";
}
?>
使用curl与正则表达式
<?php
// 初始化curl会话
$ch = curl_init('https://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
// 执行curl会话
$html = curl_exec($ch);
curl_close($ch);
// 正则表达式匹配图片src
$pattern = '/<img.*?src="(.*?)".*?>/i';
preg_match_all($pattern, $html, $matches);
// 输出所有匹配的图片src
foreach ($matches[1] as $match) {
echo "图片路径:" . $match . "<br>";
}
?>
提高匹配的兼容性
在实际应用中,网页的结构可能会有很多变化,因此提高正则表达式的兼容性非常重要。以下是一些提高兼容性的技巧:
- 使用非贪婪匹配(
.*?)来避免不必要的匹配。 - 使用
[]来匹配一组字符,例如<img.*?src="[^"]*?"可以匹配任何引号内的内容。 - 使用
.*?来匹配任意数量的任意字符,但尽可能少地匹配字符。