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

PHP用正則批量替換Img中src內容,用正則表達式獲取圖片路徑實現縮略圖功能
網上不少正則表達式只能獲取或者替換一個img的src內容,或者只能替換固定的字符串,要動態替換多個圖片內容的試了幾個小時才解決。
/**
* 圖片地址替換成壓縮URL
* @param string $content 內容
* @param string $suffix 後綴
*/
function get_img_thumb_url($content="",$suffix="!c550x260.jpg")
{
// by http://www.manongjc.com/article/1319.html
$pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
$content = preg_replace($pregRule, '<img src="${1}'.$suffix.'" style="max-width:100%">', $content);
return $content;
}
實例使用代碼:
//by http://www.manongjc.com
$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>
相關文章
相關標籤/搜索