Replace URLs in text with HTML links

后端 未结 17 1773
栀梦
栀梦 2020-11-22 11:27

Here is a design though: For example is I put a link such as

http://example.com

in textarea. How do I get PHP t

17条回答
  •  心在旅途
    2020-11-22 11:44

    I know this answer has been accepted and that this question is quite old, but it can be useful for other people looking for other implementations.

    This is a modified version of the code posted by: Angel.King.47 on July 27,09:

    $text = preg_replace(
     array(
       '/(^|\s|>)(www.[^<> \n\r]+)/iex',
       '/(^|\s|>)([_A-Za-z0-9-]+(\\.[A-Za-z]{2,3})?\\.[A-Za-z]{2,4}\\/[^<> \n\r]+)/iex',
       '/(?(?=]*>.+<\/a>)(?:]*>.+<\/a>)|([^="\']?)((?:https?):\/\/([^<> \n\r]+)))/iex'
     ),  
     array(
       "stripslashes((strlen('\\2')>0?'\\1\\2 \\3':'\\0'))",
       "stripslashes((strlen('\\2')>0?'\\1\\2 \\4':'\\0'))",
       "stripslashes((strlen('\\2')>0?'\\1\\3 ':'\\0'))",
     ),  
     $text
    );
    

    Changes:

    • I removed rules #2 and #3 (I'm not sure in which situations are useful).
    • Removed email parsing as I really don't need it.
    • I added one more rule which allows the recognition of URLs in the form: [domain]/* (without www). For example: "example.com/faq/" (Multiple tld: domain.{2-3}.{2-4}/)
    • When parsing strings starting with "http://", it removes it from the link label.
    • Added "target='_blank'" to all links.
    • Urls can be specified just after any(?) tag. For example: www.example.com

    As "Søren Løvborg" has stated, this function does not escape the URLs. I tried his/her class but it just didn't work as I expected (If you don't trust your users, then try his/her code first).

提交回复
热议问题