Replace all URLs in text to clickable links in PHP

前端 未结 2 640
猫巷女王i
猫巷女王i 2021-01-17 02:21

I have a web application written with PHP. I wanted to find all URLs inside users comments and change them to clickable links. I searched many websites and pages and found t

相关标签:
2条回答
  • 2021-01-17 03:00
    function convert($input) {
       $pattern = '@(http(s)?://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
       return $output = preg_replace($pattern, '<a href="http$2://$3">$0</a>', $input);
    }
    

    demo

    0 讨论(0)
  • 2021-01-17 03:04
    function convert($input) {
       $pattern = '@(http(s)?://)?(([a-zA-Z0-9])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
       return $output = preg_replace($pattern, '<a href="http$2://$3">$0</a>', $input);
    }
    

    This is an update of the @splash58 dude answer to handle the URL which starts with number instead of letter. Example is 11hub.net or 9gag.com

    Thank you splash58 for the great answer!

    0 讨论(0)
提交回复
热议问题