本文實(shí)例講述了PHP基于正則批量替換Img中src內(nèi)容實(shí)現(xiàn)獲取縮略圖的功能。分享給大家供大家參考,具體如下:
這里PHP用正則批量替換Img中src內(nèi)容,實(shí)現(xiàn)獲取圖片路徑縮略圖的功能
網(wǎng)上很多正則表達(dá)式只能獲取或者替換一個(gè)img的src內(nèi)容,或者只能替換固定的字符串,要?jiǎng)討B(tài)替換多個(gè)圖片內(nèi)容的試了幾個(gè)小時(shí)才解決。
/** * 圖片地址替換成壓縮URL * @param string $content 內(nèi)容 * @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; }
實(shí)例使用代碼:
$content = '<a href="#" rel="external nofollow" rel="external nofollow" ><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);
輸出結(jié)果:
復(fù)制代碼 代碼如下:
<a href="#" rel="external nofollow" rel="external nofollow" ><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>
PS:這里再為大家提供2款非常方便的正則表達(dá)式工具供大家參考使用:
JavaScript正則表達(dá)式在線測試工具:
http://tools.jb51.net/regex/javascript
正則表達(dá)式在線生成工具:
http://tools.jb51.net/regex/create_reg
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php正則表達(dá)式用法總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。
【網(wǎng)站聲明】本站除付費(fèi)源碼經(jīng)過測試外,其他素材未做測試,不保證完整性,網(wǎng)站上部分源碼僅限學(xué)習(xí)交流,請勿用于商業(yè)用途。如損害你的權(quán)益請聯(lián)系客服QQ:2655101040 給予處理,謝謝支持。