preg_replace中Regex的反向引用

來源:互聯網
上載者:User

最近遇到一個問題,要將一篇日誌中的所有img中的src的取出來,然後根據src的內容重建src,做PHP中使用函數preg_replace(),利用了Regex的反向引用:

$content = '文字文字<img src="http://www.baidu.com/img/baidu_logo_jr_1008_qx.gif>;其他文字&lt;img src="http://list.image.baidu.com/t/image_category/res/Gangtai/Ye_Xuan.jpg" alt="" width="95" height="115" >;';

function img_convert($img,$param){
$filepath = getBlogPicUrl($img); //調用getBlogPicUrl()重建新的src值
$param= str_replace("\\",$param);
$str ='img src="http://www.codebean.cn/wp-admin/'.$filepath.'" alt="" />';
}

function getBlogPicUrl($img){
//重建src值的代碼
}

$content = preg_replace("/\/ie","img_convert('$2','$1$3')",$content);

這裡使用了正則的反向引用,在調用img_convert()函數時,傳給img_convert()的即是Regex的分別匹配三個()的值,分別按順序為$1,$2,$3,也可是\\1,\\2,\\3 這種形式.

另外我在preg_replace的替換部分直接使用了函數img_convert(),這需要在Regex中加個參數e。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.