PHP - Add link to a URL in a string

后端 未结 3 1193
花落未央
花落未央 2020-11-30 12:49

I have a function that will add the tag before a link and after the link. However, it breaks for some webpages. How would

相关标签:
3条回答
  • 2020-11-30 13:08
    function processString($s){
      return preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1">$1</a>', $s);
    }
    

    Found it here

    0 讨论(0)
  • 2020-11-30 13:34
    function processString($s) {
        return preg_replace('/https?:\/\/[\w\-\.!~#?&=+\*\'"(),\/]+/','<a href="$0">$0</a>',$s);
    }
    
    0 讨论(0)
  • 2020-11-30 13:34

    It breaks for all URLs that contain "special" HTML characters. To be safe, pass the three string components through htmlspecialchars() before concatenating them together (unless you want to allow HTML outside the URL).

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