如何在php超链接一个网址或非网址


How to hyperlink a web address or a non web address in php

我有一个网站,用户输入文章和他们的参考(像维基百科)。保存在数据库中的引用包括网址和非网址。目前我超链接脚本使用谷歌的搜索?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

它应该去谷歌搜索?q

advance thanks for your help

您将使用正则表达式来查看它是否是链接并使其成为链接。正则表达式还确保它是链接的有效语法。

 $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>';
 }

您可以检查://是否存在,以查看输入的数据是否为链接。它并不完美,但您可以调整它以满足您的需求:

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

不可能自动检测您的引用是否为web地址。你必须检查引用是否为URL。

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