DIV CSS 佈局教程網

把文字中的 URL 轉為可點擊連結的 JS 與 PHP 自訂函式
編輯:關於JavaScript     

這幾天寫一個小程式時,需要用正則表達式匹配使用者輸入文字中的 URL 地址,然後把 URL 替換成可以點擊的連結。URL 的匹配在做驗證處理時常會用到,這裡把整合的一個較完整的表達式給出來:

var URL = /(https?:\/\/|ftps?:\/\/)?((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(:[0-9]+)?|(localhost)(:[0-9]+)?|([\w]+\.)(\S+)(\w{2,4})(:[0-9]+)?)(\/?( [\w#!:.?+=&%@!\-\/]+))?/ig;

這個表達式可以匹配 http、https、ftp、ftps 以及 IP 地址的 URL,算是較為完善。利用它我寫了兩個小函式,把使用者留言中的 URL 替換成可點擊的連結,核心就是借助 replace() 函式來完成替換。

JavaScript 版:

/**
 * JavaScript 版本
 * 將 URL 地址轉化為完整的 A 標籤連結程式碼
 */
var replaceURLToLink = function(text){
  text = text.replace(URL, function(url){
    var urlText = url;
    if(!url.match('^https?:\/\/')){
      url = 'https://' + url;
    }
    return '<a href="' + url + '">' + urlText + '</a>';
  });
  return text;
};

PHP 版:

/**
 * PHP 版本,在 Silva 程式碼的基礎上修改
 * 將 URL 地址轉化為完整的 A 標籤連結程式碼
 */
function replace_URLtolink($text){
  // 抓出任何看起來像 URL 的內容
  $urls = array();
  $scheme = '(https?:\/\/|ftps?:\/\/)?';
  $www = '([\w]+\.)';
  $local = 'localhost';
  $ip = '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})';
  $name = '([\w0-9]+)';
  $tld = '(\w{2,4})';
  $port = '(:[0-9]+)?';
  $the_rest = '(\/?( [\w#!:.?+=&%@!\-\/]+))?';
  $pattern = $scheme.'('.$ip.$port.'|'.$www.$name.$tld.$port.'|'.$local.$port.')'.$the_rest;
  $pattern = '/'.$pattern.'/is';

  // 取得所有 URL
  $c = preg_match_all($pattern, $text, $m);
  if ($c){
    $urls = $m[0];
  }

  // 替換所有 URL
  if (! empty($urls)){
    foreach ($urls as $url){
      $pos = strpos('https://', $url);
      if (($pos && $pos != 0) || !$pos){
        $fullurl = 'https://'.$url;
      } else {
        $fullurl = $url;
      }
      $link = '<a href="'.$fullurl.'">'.$url.'</a>';
      $text = str_replace($url, $link, $text);
    }
  }
  return $text;
}

兩個版本思路一致:先用正則找出文字中所有 URL,若缺少協議頭則補上 https://,再替換成完整的 a 標籤。JS 版用 replace 搭配回呼函式處理,PHP 版則用 preg_match_all 抓出全部匹配後逐一 str_replace,可依開發環境選用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved