//富文本圖片Begin if($data["content"]) { preg_match_all('/<img(.*)src="([^"]+)"[^>]+>/isU',$data["content"],$matches); $img = ""; if(!empty($matches)) { //注意,上面的正則表達式說明src的值是放在數組的第三個中 $img = $matches[2]; }else { $img = ""; } if (!empty($img)) { //$img_url = $request->domain(); $img_url = "http://".$_SERVER['SERVER_NAME']; $patterns= array(); $replacements = array(); foreach($img as $imgItem) { if(strpos($imgItem,"http") === false) { $final_imgUrl = $img_url.$imgItem; $replacements[] = $final_imgUrl; $img_new = "/".preg_replace("/\//i","\/",$imgItem)."/"; $patterns[] = $img_new; } } //讓數組按照key來排序 ksort($patterns); ksort($replacements); //替換內容 $data["content"] = preg_replace($patterns, $replacements, $data["content"]); } } //2017-09-29-End
<div><img src="/upload/20170920/sadsdsasasd.jpg" alt="圖片" title="圖片" ></div>php
<br/>正則表達式
<div><img src="http://xxx.com/upload/20170920/sadsdsasasd.jpg" alt="圖片" title="圖片" ></div><div>數組
第二種狀況:dom
base64轉碼圖片返回路徑編碼
//富文本圖片Begin if($data["content"]) { preg_match_all('/<img(.*)src="([^"]+)"[^>]+>/isU',$data["content"],$matches); $img = ""; if(!empty($matches)) { //注意,上面的正則表達式說明src的值是放在數組的第三個中 $img = $matches[2]; }else { $img = ""; } if (!empty($img)) { $img_url = $request->domain(); $patterns= array(); $replacements = array(); foreach($img as $imgItem) { if(strpos($imgItem,"http") === false) { //判斷是否Base64編碼的img if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgItem, $result)) { //獲取圖片後綴 $type = $result[2]; //上傳目錄 $new_file = "./uploads/".date("Ymd",time())."/"; //判斷目錄是否存在,不存在建立 if(!file_exists($new_file)) { //檢查是否有該文件夾,若是沒有就建立,並給予最高權限 mkdir($new_file, 0700); } //上傳圖片到目錄路徑 $new_file = $new_file.time().rand(1, 99).".{$type}"; //文件保存 if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $imgItem)))) { $final_imgUrl = $img_url.ltrim($new_file, "."); $replacements[] = $final_imgUrl; //$img_new = "/".preg_replace("/\//i","\/",$imgItem)."/"; $patterns[] = $imgItem; } } } } //讓數組按照key來排序 ksort($patterns); ksort($replacements); //替換內容 $data["content"] = str_replace($patterns, $replacements, $data["content"]); //$data["content"] = preg_replace($patterns, $replacements, $data["content"]); } } //2017-09-29-End
最簡潔:url
function get_img_thumb_url($content="") { $url = config('wxconfig.img_http'); $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/"; $content = preg_replace($pregRule, '<img src="'.$url.'${1}" style="max-width:100%">', $content); return $content; }