2014-11-20 114 views
0

我有一個腳本,使鏈接(http,https和www)在一個句子中可點擊。問題是我只能有一個鏈接。我可以通過任何類型的if語句中的循環來解決這個問題嗎?PHP通過正則表達式匹配文本超鏈接

$text = "Both www.google.com and http://www.google.com/calendar/ are links"; 

/** 
* Make clickable links from URLs in text. 
*/ 
function make_clickable($text) { 

    // Force http to www. 
    $text = preg_replace("(www\.)", "http://www.", $text); 

    // Delete duplicates after force. 
    $text = preg_replace("(http://http://www\.)", "http://www.", $text); 
    $text = preg_replace("(https://http://www\.)", "https://www.", $text); 

    // The RegEx. 
    $regExUrl = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 

    // Check if there is a URL in the text. 
    if(preg_match($regExUrl, $text, $url)) { 

    // Make the URLs hyper links. 
    $text = preg_replace(
     $regExUrl, 
     '<a href="' . $url[0] . '" target="_blank">' . $url[0] . '</a>', 
     $text 
    ); 

    }  

    return $text; 

} 

echo make_clickable($text); 

結果: 兩個http://www.google.comhttp://www.google.com是鏈接

在此先感謝。

+0

到底是什麼問題了嗎?這似乎正在按預期工作... – 2014-11-20 22:17:02

+0

不,請查看變量中的輸入鏈接。輸出只是給了我兩個(兩次)的第一個鏈接。如果輸入是http://stackoverflow.com/和http://google.com,我將獲得兩次http://stackoverflow.com/。因此,我想可能需要一個循環。你明白嗎? – Treps 2014-11-20 22:20:16

回答

1

你不需要任何循環。試試這個:

/** 
* Make clickable links from URLs in text. 
*/ 

    function make_clickable($text) { 

     // Force http to www. 
     $text = preg_replace("(www\.)", "http://www.", $text); 

     // Delete duplicates after force. 
     $text = preg_replace("(http://http://www\.)", "http://www.", $text); 
     $text = preg_replace("(https://http://www\.)", "https://www.", $text); 

     // The RegEx. 
     $regExUrl = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 

     // Check if there are URLs in the text then replace all 
     $text = preg_replace_callback($regExUrl, function($matches) { 
      return '<a href="' . $matches[0] . '" target="_blank">' . $matches[0] . '</a>'; 
     }, $text); 

     return $text; 
    } 

編號:preg_replace_callback()

+0

你是男人,非常感謝你!它工作完美! :) – Treps 2014-11-20 22:34:45

+1

@Treps不客氣。 :-) – thecodeparadox 2014-11-20 22:37:02