2012-05-06 106 views
0

我想在我的網站上實現以下功能。當用戶發佈內容時,他也可以包含一個鏈接,這是鏈接到圖片。想象一下,一個用戶的帖子是這樣的:php - 在文本中找到圖像鏈接並將其轉換爲鏈接

Hello look at this awesome picture. It is hilarious isn't it? 
http://www.google.com/image.jpg 

然後文本應該轉換爲:

Hello look at this awesome picture. It is hilarious isn't it? 
<a target="_blank" href="http://www.google.com/image.jpg"> 
    <img src="http://www.google.com/image.jpg" alt=""/> 
</a> 

所以我需要一些PHP腳本,通過文字搜索鏈接,如果它發現一個鏈接,檢查它是否鏈接到圖片。它還需要能夠識別不以http開頭的鏈接,以及以https開頭的鏈接。

你會怎麼做?

感謝很多:)

丹尼斯

回答

2

怎麼樣這兩個環節合併:

best way to determine if a URL is an image in PHP

PHP Regular Expression Text URL to HTML Link

$url="http://google.com/image.jpg"; 

function isImage($url){ 
    $pos = strrpos($url, "."); 
    if ($pos === false) 
     return false; 
    $ext = strtolower(trim(substr($url, $pos))); 
    $imgExts = array(".gif", ".jpg", ".jpeg", ".png", ".tiff", ".tif"); // this is far from complete but that's always going to be the case... 
    if (in_array($ext, $imgExts)) 
     return true; 
return false; 
} 

$test=isImage($url); 
if($test){ 
    $pattern = '/((?:[\w\d]+\:\/\/)?(?:[\w\-\d]+\.)+[\w\-\d]+(?:\/[\w\-\d]+)*(?:\/|\.[\w\-\d]+)?(?:\?[\w\-\d]+\=[\w\-\d]+\&?)?(?:\#[\w\-\d]*)?)/'; 
    $replace = '<a href="$1">$1</a>'; 
    $msg = preg_replace($pattern , $replace , $msg); 
    return stripslashes(utf8_encode($msg)); 
} 
+1

謝謝!我會嘗試一個:) – weltschmerz

+1

太棒了,很高興幫助! –

相關問題