在使用 Markdown 編寫文章之后,經(jīng)常需要發(fā)布到不同的平臺,這里會遇到一個問題,文章的圖片需要手動的進行上傳,管理起來非常不方便,因此,強烈建議將圖片統(tǒng)一上傳到圖床中,這樣的話一篇文章就可以輕松的同步到各大平臺上面了。下面,用 PHP 來實現(xiàn)該功能,選用 七牛云 作為圖床
創(chuàng)建并進入項目
$ mkdir markdown-images-to-qiniu $ cd markdown-images-to-qiniu
安裝七牛官方的擴展
$ composer require qiniu/php-sdk
實現(xiàn)思路很簡單
● 讀取 makrdown 文件
● 正則匹配出所有的圖片
● 依次上傳圖片
● 將文章圖片的地址替換為圖床地址
● 保存替換后的文章
以下是具體的實現(xiàn),首先在項目目錄下創(chuàng)建腳本 index.php,
?php require 'vendor/autoload.php'; use Qiniu\Auth; use Qiniu\Storage\UploadManager; // 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 = '你的七??臻g名'; // 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} 上傳成功。\n"; } else { echo "{$uploadPath} 上傳失敗。\n"; } } // 5. 保存替換后的文章 file_put_contents($file, $content);
使用
$ php index.php test.md
以上就是PHP腳本實現(xiàn)Markdown文章上傳到七牛圖床的詳細內(nèi)容,如果大家還有任何補充的內(nèi)容可以聯(lián)系腳本之家小編。
標簽:黃南 湛江 鎮(zhèn)江 南陽 宜賓 婁底 銅川 寶雞
巨人網(wǎng)絡(luò)通訊聲明:本文標題《PHP實現(xiàn)Markdown文章上傳到七牛圖床的實例內(nèi)容》,本文關(guān)鍵詞 PHP,實現(xiàn),Markdown,文章,上,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。