基本原理

  1. 使用file_get_contentscurl获取网页内容。
  2. 解析网页内容,提取图片的src属性。
  3. 将图片下载到本地。

使用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>";
}
?>

提高匹配的兼容性

在实际应用中,网页的结构可能会有很多变化,因此提高正则表达式的兼容性非常重要。以下是一些提高兼容性的技巧:

  1. 使用非贪婪匹配(.*?)来避免不必要的匹配。
  2. 使用[]来匹配一组字符,例如<img.*?src="[^"]*?"可以匹配任何引号内的内容。
  3. 使用.*?来匹配任意数量的任意字符,但尽可能少地匹配字符。

总结