創(chuàng)建并進(jìn)入項(xiàng)目
$ mkdir markdown-images-to-qiniu $ cd markdown-images-to-qiniu
安裝七牛官方的擴(kuò)展
$ composer require qiniu/php-sdk
實(shí)現(xiàn)思路很簡單
● 讀取 makrdown 文件
● 正則匹配出所有的圖片
● 依次上傳圖片
● 將文章圖片的地址替換為圖床地址
● 保存替換后的文章
以下是具體的實(shí)現(xiàn),首先在項(xiàng)目目錄下創(chuàng)建腳本 index.php,
<?php require 'vendor/autoload.php'; use QiniuAuth; use QiniuStorageUploadManager; // 1. 讀取 `makrdown` 文件 $file = $argv[1]; if(! file_exists($file) ){ return "找不到文件{$file}"; } $orginalContent = file_get_contents($file); // 2. 正則匹配出所有的圖片 preg_match_all( '//', $orginalContent, $matches, PREG_PATTERN_ORDER ); $mdImageArr = $matches[0]; if(! count($mdImageArr) ){ return "無需上傳圖片"; } // 3. 依次上傳圖片 $accessKey = '你的 AccessKey'; $secretKey = '你的 SecretKey'; $bucket = '你的七牛空間名'; // eg. mindgeek $url = "空間所綁定的域名"; // eg. http://qiniu.site.com $auth = new Auth($accessKey, $secretKey); $token = $auth->uploadToken($bucket); $uploadMgr = new UploadManager(); $content = $orginalContent; foreach ($mdImageArr as $image) { $start = mb_strpos($image, '](') + 2; $localPath = mb_substr($image, $start, -1); $extension = pathinfo($localPath)['extension']; $uploadPath = uniqid(). ".". $extension; list($ret, $error) = $uploadMgr->putFile($token, $uploadPath, $localPath); if(! $error ){ // 4. 將文章圖片的地址替換為圖床地址 $content = str_replace($localPath, $url.$uploadPath, $content); echo "{$uploadPath} 上傳成功。 "; } else { echo "{$uploadPath} 上傳失敗。 "; } } // 5. 保存替換后的文章 file_put_contents($file, $content);
使用
$ php index.php test.md
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com