dongyi0114 2010-01-26 11:53
浏览 31
已采纳

用<A>标记替换非HTML链接

I have a block of code that will take a block of text like the following:

Sample text sample text http://www.google.com sample text

Using the preg_replace_callback method and the following regular expression:

preg_replace_callback('/http:\/\/([,\%\w.\-_\/\?\=\+\&\~\#\$]+)/',
    create_function(
        '$matches',
        '$url = $matches[1]; 
        $anchorText = ( strlen($url) > 35 ? substr($url, 0, 35).\'...\' : $url); 
        return \'<a href="http://\'. $url .\'">\'. $anchorText .\'</a>\';'),
    $str);

Will convert the sample text to look like:

Sample text sample text < a href="http://www.google.com">http://www.google.com< /a> sample text

My problem now is that we have introduced a rich text editor that can create links before being sent to the script. I need to update this piece of code so that it will ignore any URLs that are already inside an tag.

  • 写回答

1条回答 默认 最新

  • drdawt9210 2010-01-26 12:25
    关注

    Add code to the beginning of the pattern to capture an opening anchor tag, and then do not perform the callback code when it has captured something:

    /(<a[^>]*>)?http:\/\/([,\%\w.\-_\/\?\=\+\&\~\#\$]+)/
    

    You will then need to add an if to your lamda function to see if there is anything in $matches[1] (Don't forget to increment your captures as well)

    You cannot use a negative look behind assertion here as the capture is not a fixed length, but you could use a negative look ahead assertion for the closing tag so it drops the entire match:

    /(<a[^>]*>)?http:\/\/([,\%\w.\-_\/\?\=\+\&\~\#\$]+)(?!<\/a>)/
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?