普通网友 2013-01-20 21:36
浏览 376
已采纳

重写字符串中的多个链接URL

I have a long string that contains multiple HTML links that looks like this:

<a href="example.com">My Link></a>

or

<a href="http://example2.com">A different Link</a>

etc.

I need to rewrite these links in PHP so that they send the traffic thru my redirector, so I can tell users they are now leaving to an external domain, etc. My redirector is located at mydomain.com/leaving.php. What I want to do is rewrite these links to something like this:

<a href="http://www.mydomain.com/leaving.php/[URL ENCODED LINK FROM ABOVE]">My Link>

Since not all urls have http:// to begin with I think I need to first strip those from all href links.

How can I grep the correct HTML links (ignoring image src) and url_encode them, and place them back in the original string.

EDIT: Just to clearify, I am not looking for help with the redirection part, just how to replace several URLs within a large string when they sometimes have http

  • 写回答

2条回答 默认 最新

  • dongtu1958 2013-01-20 22:41
    关注

    This is just a pseudo that you can modify it as you need.

    You need first a .htaccess file that contents following lines;

    RewriteEngine On
    RewriteRule ^leaving/(.*)$ leaving.php?url=$1 [L]
    

    And in leaving.php;

    $url = trim(urldecode($_GET['url']));
    // check url is exists
    if ($url == '') {
        header('Location: http://www.mydomain.com/');
        exit;
    }
    // add http if needs
    if (substr($url, 0, 7) != 'http://') {
        $url = 'http://'. $url;
    }
    
    // send it to target
    header('Location: '. $url);
    exit;
    

    UPDATE:

    If you trying this on server-side, it's useless, cos if PHP sent output once, then u cannot use preg's anymore. So, if want to do this on client-side, following code or somthing like will help you.

    var links = document.getElementsByTagName("a"),
        link, href, i = 0;
    while (link = links[i++]) {
        // get real url applying getAttribute with "2" params
        if ((href = link.getAttribute("href", 2)) !== null
                // skip non-href links
                && href.charAt(0) !== "#") {
            // add http if not exists
            if (href.substring(0, 7) !== 'http://') {
                href = "http://"+ href
            }
            link.href = "http://www.mydomain.com/leaving/"+ href;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里