PHP用正則批量替換Img中src內容,用正則表達式獲取圖片路徑實現縮略圖功能


PHP用正則批量替換Img中src內容,用正則表達式獲取圖片路徑實現縮略圖功能

網上很多正則表達式只能獲取或者替換一個img的src內容,或者只能替換固定的字符串,要動態替換多個圖片內容的試了幾個小時才解決。

/**
* 圖片地址替換成壓縮URL
* @param string $content 內容
* @param string $suffix 后綴
*/
function get_img_thumb_url($content="",$suffix="!c550x260.jpg")
{
$pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
$content = preg_replace($pregRule, '<img src="${1}'.$suffix.'" style="max-width:100%">', $content);
return $content;
}

實例使用代碼:
$content = '<a href="#"><img class="center" src="https://xxx.com/styles/images/default.jpg"></a>'
.'<p><img class="center" src="https://img.xxx.com/images/219_Ig5eZI.jpg" style="max-width: 100%;"></p>';
$newct = get_img_thumb_url($content);
print_r($newct);

輸出結果:
<a href="#"><img src="https://xxx.com/styles/images/default.jpg!c550x260.jpg" style="max-width:100%"></a><p><img src="https://img.xxx.com/images/219_Ig5eZI.jpg!c550x260.jpg" style="max-width:100%"></p>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM