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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化