2011-10-17 122 views
2

我有一個網站是用戶輸入文章和他們的參考(如維基百科)。保存在數據庫中的參考文獻包括網址和非網址。目前,我使用谷歌搜索?q及其正常工作來超鏈接腳本。如何超鏈接的網址或非網址在php

 echo("<br><a rel=nofollow target=_blank href='http://www.google.com/search?q=".urlencode($row['ref'])."' class=art>$row[ref]</a>"); 

我想知道是否它能夠自動地檢測我的引用作爲一個網址或不是。如果是一個網絡地址,然後當用戶點擊超鏈接直接進入該網站,如果沒有它應該超鏈接到谷歌搜索。

例如:

如果用戶輸入該鏈接作爲reference.hyper鏈路應該是此網絡地址

 http://www.washingtonpost.com/sports/capitals 
     or 
     www.washingtonpost.com/sports/capitals 
     or 
     washingtonpost.com/sports/capitals 

,或者如果用戶輸入的參考如下

 washingtonpost+sports+capitals 

它應該去谷歌搜索?q

提前感謝您的幫助

回答

1

您將使用常規表達式來查看它是否是鏈接並將其設置爲鏈接。正則表達式也確保它是鏈接的有效語法。

$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 
// The Text you want to filter for urls 
$text = "http://www.google.com"; #The text you want to filter goes here 
// Check if there is a url in the text 
if(preg_match($reg_exUrl, $text, $url)) { 
    // make the urls hyper links 
    echo preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text); 
} else { 
    // if no urls in the text just return the text 
    echo '<a href="http://www.google.com/search?q=',urlencode($text),'">',$text,'</a>'; 
} 
1

您可以檢查是否存在://以查看輸入的數據是否爲鏈接。這不是完美的,但你可以調整它來滿足您的需求:

$URL = 'http://www.google.com?/q=' . urlencode($Reference); 
if (strpos($Reference, '://') !== false) 
{ 
    $URL = $Reference; 
} 

echo '<a href="' . $Reference . '">' . $Reference . '</a>'; 
1

這是不可能自動檢測您參考作爲一個網頁地址,或沒有。你必須檢查引用是否是URL。

function isValidURL($url) { 
    return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url); 
}