Replace URLs in text with HTML links

后端 未结 17 1987
栀梦
栀梦 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 12:02

    While matching the full url spec is difficult, here's a regular expression that generally does a good job:

    ([\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?)
    

    To use this in preg_replace, however, you need to escape it. As so:

    $pattern = "/([\\w-]+(\\.[\\w-]+)*@([a-z0-9-]+(\\.[a-z0-9-]+)*?\\.[a-z]{2,6}|(\\d{1,3}\\.){3}\\d{1,3})(:\\d{4})?)/";
    $replaced_texttext = preg_replace($pattern, '$0', $text);
    

提交回复
热议问题