duanhuanbo5225 2011-08-23 17:09
浏览 49
已采纳

StackOverflow样式A正则表达式中的Href自动链接

I am using the below function to search for text links and convert them to a hyperlink. First of all is it correct? It appears to work but do you know of a (perhaps malformed) url that would break this function?

My question is whether it is possible to get this to support port numbers as well, for example stackoverflow.com:80/index will not be converted as the port is not seen as a valid part of the url.

So in summary I am looking for Stackoverflow style url recognition, which I believe is a custom addition to Markdown.

  /**
   * Search for and create links from urls
   */
  static public function autoLink($text) {
    $pattern = "/(((http[s]?:\/\/)|(www\.))(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+(\.[a-z]{2,2})?)\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1})/is";
    $text = preg_replace($pattern, " <a href='$1'>$1</a>", $text);
    // fix URLs without protocols
    $text = preg_replace("/href='www/", "href='http://www", $text);

    return $text;
  } 

Thanks for your time,

  • 写回答

3条回答 默认 最新

  • duannuochi3549 2011-08-24 12:45
    关注

    You should also look at the answers to this question: How to mimic StackOverflow Auto-Link Behavior


    I have ended up combining the answers I have got both at stack overflow and talking to colleagues. The below code is the best we could come up with.

    /**
       * Search for and create links from urls
       */
      static public function autoLink($text) {
        $pattern = "/\b((?P<protocol>(https?)|(ftp)):\/\/)?(?P<domain>[-A-Z0-9\\.]+)[.][A-Z]{2,7}(([:])?([0-9]+)?)(?P<file>\/[-A-Z0-9+&@#\/%=~_|!:,\\.;]*)?(?P<parameters>\?[A-Z0-9+&@#\/%=~_|!:,\\.;]*)?/ise";
    $text = preg_replace($pattern, "' <a href=\"'.htmlspecialchars('$0').'\">$0</a>'", $text);
    
        // fix URLs without protocols
        $text = preg_replace("#href='www#i", "href='http://www", $text);
        $text = preg_replace("#href=['\"](?!(https?|ftp)://)#i", "href='http://", $text);
    
        return $text;
      } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能