2012-03-10 59 views
3

可能重複:
How to add anchor tag to a URL from text input
PHP Regular expression to match keyword outside HTML tag <a>PHP中使用的preg_replace將URL轉換爲鏈接.....有時....:P

好了,所以我使用OsTicket(電子郵件票據系統),並將其轉換爲使用HTML格式的電子郵件進出。它被黑了,但它的工作。

好,此刻有在那裏的功能稱爲「clickableURLS」 ......

function clickableurls($text) { 

     //Not perfect but it works - please help improve it. 
     $text=preg_replace('/([^(\'|")]((f|ht){1}tp(s?):\/\/)[[email protected]:%_\+.~#?&;\/\/=]+[^(\'|")])/','<a href="\\1" target="_blank">\\1</a>', $text); 
     $text=preg_replace("/(^|[ \\n\\r\\t])([^('|\")]www\.([a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+)(\/[^\/ \\n\\r]*)*[^('|\")])/", 
       '\\1<a href="http://\\2" target="_blank">\\2</a>', $text); 
     $text=preg_replace("/(^|[ \\n\\r\\t])([^('|\")][_\.0-9a-z-][email protected]([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}[^('|\")])/",'\\1<a href="mailto:\\2" target="_blank">\\2</a>', $text); 


     return $text; 
    } 

正如你所看到的,它基本上需要一個URL(搜索HTTP或HTTPS或www)和然後在那裏添加適當的mumbo jumbo。

好....

我現在有一個所見即所得的設置....所以,如果我們的技術人員的一個usees所見即所得創建鏈接的正確方法......自動創建的代碼。 ...然後clickableurls函數ALSO查找已經在文本中的http並將其再次轉換爲...

所以我基本上試圖找出處理該問題的最佳方法。我確實希望有兩個選項......並且正在考慮做一個IF語句,但是不會改變preg_replace使得更有意義?

有什麼想法?再次感謝溢出社區!

+0

有你的正則表達式的問題。不知道具體的細節,它很難幫助你。 – sln 2012-03-10 23:12:59

+0

搜索「Linkify URL」 - 很多答案! ([這是我使用的](http://stackoverflow.com/a/5291451/433790))。 – ridgerunner 2012-03-11 04:29:16

回答

3

我可以嘗試幫助您翻譯第一個preg_replace()正則表達式中的內容。
這就是我可以做的最好的,因爲我不知道你的意圖。我已經推斷了一些意圖,
但它取決於你來確定。

當正則表達式很複雜時,塊格式化有助於輕鬆查看複雜性。

([^(\'|")]((f|ht){1}tp(s?):\/\/)[[email protected]:%_\+.~#?&;\/\/=]+[^(\'|")])

(         # Capture group 1 
    [^'"]        # Consume a character that is not single nor double quote 
    (         # Capture group 2 
     (?:ftp|https?):      # Either ftp, OR http (optional s) string literal 
     //         # Literl double forward shashes 
    )         # End capt grp 2 
    [[email protected]:%_+.~#?&;/=]+   # 1 or more (greedy) of the characters in this class 
    [^'"]        # Consume a character that is not single nor double quote 
)         # End capt grp 1