php 正则获取字符串中所有图片链接地址并下载图片
/** * 获取图片的绝对地址 * @param string $content * @return mixed * @Author: code.cent123.com */ function getImageUrl(string $content = "") { //$pattern = "/src=[\"\'](\S*\.(jpg|png))[\"\']/i"; //$pattern = "/https?:\/\/(\S*\.(jpg|png))/Ui"; //$pattern = "/https?:\/\/(\S*\.com)(\S*\.(jpg|png|gif|jpeg))/Ui"; $pattern = "#https?://(\S*\.com)(\S*\.(jpg|png|gif|jpeg))#Ui"; preg_match_all($pattern, $content, $matches); return $matches; } /** * 下载图片 * @param $arr * @return void * @Author: code.cent123.com */ function downloadImage($arr): void { foreach ($arr[0] as $key => $val) { //$path_parts = pathinfo($val); //$dirname = str_replace($arr[1][$key], "", $path_parts['dirname']); //$filename = $dirname . '/' . $path_parts['basename']; $path_parts = pathinfo($arr[2][$key]); $dirname = $path_parts['dirname']; $filename = $arr[2][$key]; if (!is_dir($dirname)) { mkdir($dirname, 0777, true); } print_r($val."\n"); file_put_contents($filename, file_get_contents($val)); } }
测试
$path = 'E:\www\shop\template\test.html'; $arr = getImageUrl(file_get_contents($path), ''); print_r($arr); downloadImage($arr);