douxie1692 2013-05-05 22:56
浏览 33

PHP:正确地将地址转换为字符串中的可点击链接

I need to automatically parse a string and find if a link to my site is present, automatically replace the address by a clickeable HTML link.

Supposing my site adresses are www.mysite.com + wap.mysite.com + m.mysite.com, I need to convert:

My pictures at m.mysite.com/user/id are great.

to:

My pictures at <a href="/user/id" target="_blank">mysite.com/user/id</a> are great.

The question is how to do this (with ereg_replace?) instead of using tons of lines of code.

Notice that the result must be a relative URL, so that the current protocol and subdomain is used for the target link. If the user is in the m subdomain of the HTTPS version, the target will be the m subdomain of the HTTPS protocol and so on. Only links to mysite.com must be linked, any other links must be treated as ordinary plain text. Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongyuan1984 2013-05-05 23:35
    关注

    First piece of advice, stay away from ereg, it's been deprecated for a long time. Second, you can probably google and experiment to concoct a preg expression that works well for you, so tweak what I have here to suit your needs.

    I was able to put together a fairly simple regex pattern to search for the URLs.

    preg_match("/m.mysite.com\S+/", $str, $matches);
    

    Once you have the URLs, I'd suggest parse_url instead of regex.

    And here is the code

    $sSampleInput = 'My pictures at http://m.mysite.com/user/id are great.';
    
    // Search for URLs but don't look for the scheme, we'll add that later
    preg_match("/m.mysite.com\S+/", $sSampleInput, $aMatches);
    
    $aResults = array();
    foreach($aMatches as $sUrl) {
        // Tack a scheme afront the URL
        $sUrl = 'http://' . $sUrl;
    
        // Try validating the URL, requiring host & path
        if(!filter_var(
            $sUrl,
            FILTER_VALIDATE_URL,
            FILTER_FLAG_HOST_REQUIRED|FILTER_FLAG_PATH_REQUIRED)) {
            trigger_error('Invalid URL: ' . $sUrl . PHP_EOL);
            continue;
        } else
            $aResults[] =
                '<a href="' . parse_url($sUrl, PHP_URL_PATH) .
                '" target="_blank">' . $sUrl . '</a>';
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题