我正在研究一些代碼,並且我已經做了足夠的工作來完成某些任務。我想在文本主體中替換圖片網址和網頁鏈接。Php preg_match和preg_replace帶有url和圖像標籤的文本
EG「這是我的文字與http://www.google.com和某些圖像http://www.somewebimage.png」
替換爲「這是我的文字與<a href="http://www.google.com">http://www.google.com</a>
和某些圖像<img src="http://www.somewebimage.png">
」
我砍得我更換網址或者IMG的鏈接,但並不both..one是在寫入的,因爲爲了
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$reg_exImg = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?(jpg|png|gif|jpeg)/';
$post = "This is my text with http://www.google.com and some image http://www.somewebimage.png";
if(preg_match($reg_exImg, $post, $img)) {
$img_post = preg_replace($reg_exImg, "<img src=".$img[0]." width='300' style='float: right;'> ", $post);
} else {
$img_post = $post;
}
if(preg_match($reg_exUrl, $post, $url)) {
$img_post = preg_replace($reg_exUrl, "<a href=".$url[0]." target='_blank'>{$url[0]}</a> ", $post);
} else {
$img_post = $post;
}
的如果我阻止了$ reg_exUrl代碼塊,我得到的圖像鏈接,如果它運行的我得到的URL鏈接。
我想要做的是一個簡單的飼料,其中的URL鏈接被和IMG的URL被嵌入.. –
第一件事,測試用圖案'preg_match'在與'preg_replace'一起使用之前是沒有用的。 –
您應該爲這兩種情況使用單一模式,然後使用'preg_replace_callback'選擇替換模板。這樣一切都是一次完成的,沒有任何東西被覆蓋。在回調函數中,您可以使用'parse_url'和'explode'來輕鬆提取文件擴展名。 –