2010-11-18 64 views
9

我有一個功能,將在鏈接之前添加<a href>標記,鏈接之後添加</a>。但是,對於某些網頁而言,它會中斷。你將如何改進這個功能?謝謝!PHP - 將鏈接添加到字符串中的URL

function processString($s) 
{ 
    // check if there is a link 

    if(preg_match("/http:\/\//",$s)) 
    { 
     print preg_match("/http:\/\//",$s); 


     $startUrl = stripos($s,"http://"); 

     // if the link is in between text 
     if(stripos($s," ",$startUrl)){ 
      $endUrl = stripos($s," ",$startUrl); 
     } 
     // if link is at the end of string 
     else {$endUrl = strlen($s);} 

     $beforeUrl = substr($s,0,$startUrl); 
     $url = substr($s,$startUrl,$endUrl-$startUrl); 
     $afterUrl = substr($s,$endUrl); 

     $newString = $beforeUrl."<a href=\"$url\">".$url."</a>".$afterUrl; 

     return $newString; 
    } 

    return $s; 
} 
+0

正則表達式是有點草率,但我投入的99%,將有正確的網址,如果有的話 – AlexBrand 2010-11-18 16:53:15

+4

它打破什麼網頁? – 2010-11-18 16:54:15

+0

開始時你也會測試https,但稍後會忽略「s」。不知道,如果這導致這個錯誤,因爲我也不知道,哪些頁面被破壞;) – KingCrunch 2010-11-18 16:58:39

回答

18
function processString($s) { 
    return preg_replace('/https?:\/\/[\w\-\.!~#?&=+\*\'"(),\/]+/','<a href="$0">$0</a>',$s); 
} 
+0

我想缺少一個「=」:當url包含get參數時失敗。我只是在「&」後面添加它,現在它工作: 'preg_replace('/ https?:\/\/[\ w \ - \。!〜?&= + \ * \'「(),\ /] + /','$0',$ s)' – Narcolessico 2012-05-16 08:43:55

+4

您忘記了#內部的地址 - 所以更正確的版本是'preg_replace('/ https?:\/\/[\ w \ - \。!〜# ?&= + \ * \'「(),\ /] + /','$0',$ text)' – 2013-03-21 13:10:10

+0

我剛剛編輯了答案以反映這兩個補充。 – 2014-07-24 07:23:08

1

它打破了對包含 「特殊」 的HTML字符的所有URL。爲了安全起見,在將它們連接在一起之前,先通過htmlspecialchars()傳遞這三個字符串組件(除非你想允許HTML之外的HTML)。

1
function processString($s){ 
    return preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1">$1</a>', $s); 
} 

發現here

+0

failed here:' http://www.xyz.com/~this-does-not-work!' – stillstanding 2010-11-18 17:12:40

+0

匹配「a ... a」 - 奇怪 – AlexBrand 2010-11-18 18:51:06

+0

同樣的情況我需要它在jquery/Javascript中。任何人都可以幫忙嗎? – Yuv 2014-08-27 08:38:10