douluo6626 2011-10-25 18:33
浏览 101
已采纳

使用PHP查找字符串中的链接。 与普通链接和youtube链接不同

I have a string that contain links. I want my php to do different things with my links, depending on the url.

Answer:

function fixLinks($text)
{       
        $links = array();
        $text = strip_tags($text);    
        $pattern = '!(https?://[^\s]+)!'; 
        if (preg_match_all($pattern, $text, $matches)) {
            list(, $links) = ($matches);
        }

        $i = 0;
        $links2 = array();
        foreach($links AS $link) {
            if(strpos($link,'youtube.com') !== false) {
                $search = "!(http://.*youtube\.com.*v=)?([a-zA-Z0-9_-]{11})(&.*)?!";
                $youtube = '<a href="youtube.php?id=\\2" class="fancy">http://www.youtube.com/watch?v=\\2</a>';
                $link2 = preg_replace($search, $youtube, $link);
            } else {
                $link2 = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\-\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1" target="_blank"><u>$1</u></a>', $link);
            }
            $links2[$i] = $link2;
            $i++;     
        }
        $text = str_replace($links, $links2, $text);
        $text = nl2br($text);

    return $text;
}
  • 写回答

2条回答 默认 最新

  • duanbin4847 2011-10-25 18:44
    关注

    First of all, ditch eregi. It's deprecated and will disappear soon.

    Then, doing this in just one pass is maybe a stretch too far. I think you'll be better off splitting this into three phases.

    Phase 1 runs a regex search over your input, finding everything that looks like a link, and storing it in a list.

    Phase 2 iterates over the list, checking whether a link goes to youtube (parse_url is tremendously useful for this), and putting a suitable replacement into a second list.

    Phase 3: you now have two lists, one containing the original matches, one containing the desired replacements. Run str_replace over your original text, providing the match list for the search parameter and the replacement list for the replacements.

    There are several advantages to this approach:

    1. The regular expression for extracting links can be kept relatively simple, since it doesn't have to take special hostnames into account
    2. It is easier to debug; you can dump the search and replace arrays prior to phase 3, and see if they contain what you expect
    3. Because you perform all replacements in one go, you avoid problems with overlapping matches or replacing a piece of already-replaced text (after all, the replaced text still contains a URL, and you don't want to replace that again)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改