我有一个网站被用户输入文章和他们的参考(如维基百科)。保存在数据库中的引用包括网址和非网址。目前我使用google的搜索超链接脚本?q及其正常工作。
echo("<br><a rel=nofollow target=_blank href='http://www.google.com/search?q=".urlencode($row['ref'])."' class=art>$row[ref]</a>");
我想知道是否有可能自动将我的引用检测为网址。如果它是一个网址,那么当用户点击超链接时它会直接进入该网站,如果不是,它应该超链接到谷歌搜索
例如:
如果用户输入此链接作为参考。应该链接到此网址
http://www.washingtonpost.com/sports/capitals
or
www.washingtonpost.com/sports/capitals
or
washingtonpost.com/sports/capitals
或者如果用户输入以下参考
washingtonpost+sports+capitals
它应该去googles搜索吗?q
预先感谢您的帮助
答案 0 :(得分:1)
您可以检查是否存在://
,以查看输入的数据是否为链接。它并不完美,但您可以调整它以满足您的需求:
$URL = 'http://www.google.com?/q=' . urlencode($Reference);
if (strpos($Reference, '://') !== false)
{
$URL = $Reference;
}
echo '<a href="' . $Reference . '">' . $Reference . '</a>';
答案 1 :(得分:1)
无法自动将您的引用检测为网址。你必须检查引用是否是URL。
function isValidURL($url) {
return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}
答案 2 :(得分: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>';
}