下面的代碼檢查任何URL的字符串中的文本並將它們轉換爲可點擊的鏈接。正則表達式用鏈接替換url並添加特定的rel
我試圖獲得它,以便如果有圖像鏈接,它會在< a>標記中添加rel =「image」。如果有YouTube視頻,它會將rel =「youtube」添加到< a>標籤。
如果字符串中只有一個鏈接,它工作正常。當有多個鏈接時,所有鏈接都會獲得最後一個鏈接的相關信息。
$text = "http://site.com a site www.anothersite.com/ http://imgur.com/image.png http://youtu.be/UyxqmghxS6M here is another site";
$linkstring = preg_replace('/(http|ftp)?+(s)?:?(\/\/)?+(www.)?((\w|\.)+)+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU|be|info|co)+(\/)?(\S+)?/i', '<a rel="iframe" href="\0">\0</a>', $text);
if(preg_match('/((http:\/\/)?(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/v\/)([\w-]{11}).*|http:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*)/i', $linkstring, $vresult)) {
$pattern = "/(http|ftp)?+(s)?:?(\/\/)?+(www.)?((\w|\.)+)+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU|be|info|co)+(\/)?(\S+)?/i";
$replacement = '<a rel="youtube" href="\0">\0</a>';
$text2 = preg_replace($pattern, $replacement, $text);
$type= 'youtube';
} elseif(preg_match('/(http(s?):)?|([\/|.|\w|\s])*\.(?:jpg|gif|png|jpeg|bmp)/i', $linkstring, $vresult)) {
$pattern = "/(http|ftp)?+(s)?:?(\/\/)?+(www.)?((\w|\.)+)+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU|be|info|co)+(\/)?(\S+)?/i";
$replacement = '<a rel="image" href="\0">\0</a>';
$text2 = preg_replace($pattern, $replacement, $text);
$type= 'image';
} else {
$type = 'none';
}
echo $text, "<br />";
echo $text2, "<br />";
echo $linkstring, "<br />";
echo $type, "<br />";
我試圖改變$模式以便它匹配相同的正則表達式的YouTube或圖片鏈接,但它結束了創建鏈接的URL後的全部文本。
例子:
$text = "http://site.com a site www.anothersite.com/ http://imgur.com/image.png http://youtu.be/UyxqmghxS6M here is another site";
$linkstring = preg_replace('/(http|ftp)?+(s)?:?(\/\/)?+(www.)?((\w|\.)+)+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU|be|info|co)+(\/)?(\S+)?/i', '<a rel="iframe" href="\0">\0</a>', $text);
if(preg_match('/((http:\/\/)?(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/v\/)([\w-]{11}).*|http:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*)/i', $linkstring, $vresult)) {
$pattern = "/((http:\/\/)?(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/v\/)([\w-]{11}).*|http:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*)/i";
$replacement = '<a rel="youtube" href="\0">\0</a>';
$text2 = preg_replace($pattern, $replacement, $text);
$type= 'youtube';
} else {
$type = 'none';
}