2011-10-17 49 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); 
}