[PHP] 把字串裡含 http, https 等轉換為連結

  1. public function formatUrlsInText($text){   
  2.     $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";   
  3.     preg_match_all($reg_exUrl$text$matches);   
  4.     $usedPatterns = array();   
  5.     foreach($matches[0] as $pattern){   
  6.         if(!array_key_exists($pattern$usedPatterns)){   
  7.             $usedPatterns[$pattern]=true;   
  8.             $text = str_replace  ($pattern"<a href=".$pattern." target='_blank'>".$pattern."</a> "$text);      
  9.         }   
  10.     }   
  11.      return $text;   
  12. }  

很多時候使用者輸入網址時並不會幫你輸入 a 的 tag,於是可以使用正規表示法把含某些關鍵字的內容轉換為連結,這個 function http, https, ftp, ftps 等都可以轉換,有需要的可以試試看。

留言