php正則匹配文章中的遠程圖片地址並下載圖片到本地

來源:互聯網
上載者:User


這裡我們使用php的Regex來實現:

 代碼如下 複製代碼
$content = '這裡是文章內容,這裡插入一張圖片測試 <img src="yun_qi_img/48ef3a3e1f30e9246abc40834c086e061c95f7521.jpg">';
$content = stripslashes ( $content );
$img_array = array ();
// 匹配所有遠程圖片
preg_match_all ( "/(src|SRC)=["|'| ]{0,}(http://(.*).(gif|jpg|jpeg|bmp|png))/isU", $content, $img_array );
// 匹配出來的不重複圖片
$img_array = array_unique ( $img_array [2] );
print_r($img_array);

上面就將遠程圖片給匹配出來了,我們需要將其保持到本地。這裡需要注意兩點:

1.圖片儲存路徑(圖片儲存目錄)

2.實際訪問圖片地址

下面是完整執行個體:(你可以儲存到本機伺服器修改相應地方進行測試)

 代碼如下 複製代碼

<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>php儲存遠程圖片到本地,php正則匹配文章中的圖片地址</title>
</head>
<body>
<?php
//儲存文章中遠程圖片到本地
//作者:yanue;
// 檔案儲存目錄路徑(請更換為你自己的路徑, 你可以echo一下)
$save_path = $_SERVER ['DOCUMENT_ROOT'] . 'swfupload/attached/';
// 檔案儲存目錄URL
$save_url = '/swfupload/attached/';
$save_path = realpath ( $save_path ) . '/';
// 圖片儲存目錄
$imgPath = $save_path . date ( "Ymd" );
$imgUrl = $save_url . date ( "Ymd" );

// 建立檔案夾
if (! is_dir ( $imgPath )) {
 @mkdir ( $imgPath, 0777 );
}
$content = '這裡是文章內容,這裡插入一張圖片測試 <img src="yun_qi_img/48ef3a3e1f30e9246abc40834c086e061c95f7521.jpg">';
$content = stripslashes ( $content );
$img_array = array ();
// 匹配所有遠程圖片
preg_match_all ( "/(src|SRC)=["|'| ]{0,}(http://(.*).(gif|jpg|jpeg|bmp|png))/isU", $content, $img_array );
// 匹配出來的不重複圖片
$img_array = array_unique ( $img_array [2] );
print_r($img_array);
// 時間無限制
set_time_limit ( 0 );
foreach ( $img_array as $key => $value ) {
 $value = trim ( $value );
 // 讀取遠程圖片
 $get_file = @file_get_contents ( $value );
 // 儲存到本地圖片名稱
 $imgname = date ( "YmdHis" ) . '_' . rand ( 10000, 99999 ) . "." . substr ( $value, - 3, 3 );
 // 儲存到本地的實際檔案地址(包含路徑和名稱)
 $fileName = $imgPath . '/' . $imgname;
 // 實際訪問的地址
 $fileurl = $imgUrl . "/" . $imgname;
 // 檔案寫入
 if ($get_file) {
  $fp = @fopen ( $fileName, "w" );
  @fwrite ( $fp, $get_file );
  @fclose ( $fp );
 }
 // 替換原來的圖片地址
 $content = ereg_replace ( $value, $fileurl, $content );
}
echo $content;
?>
</body>
</html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.