donglie7778 2012-06-26 20:30
浏览 87

绝对URL的相对+基本URL?

Basically, given a base URL like

file:///path/to/some/file.html

And a relative URL like

another_file.php?id=5

I want to get out

file:///path/to/some/another_file.php?id=5

I found this script (which is the same as this one) but it doesn't seem to work on the file:// scheme. I'm doing some local tests before I go live with my code, so I'd like to work on both file:// and http://.

Any one know of a script/function that will do this?

In C#, I'd use Uri(Uri base, string rel).


The above is just an example. It should work on any URL that you could throw into <a href="xxx">.


This is the best I've got so far, but it won't handle .. and probably a few other things:

function rel2abs($base, $rel) {
    if (parse_url($rel, PHP_URL_SCHEME) != '') return $rel;
    if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;
    $parse = parse_url($base);
    $path = preg_replace('#/[^/]*$#', '', $parse['path']);
    if ($rel[0] == '/') $path = '';
    $abs = (isset($path['host'])?$path['host']:'')."$path/$rel";
    $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
    for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
    return $parse['scheme'].'://'.$abs;
}
  • 写回答

6条回答 默认 最新

  • duannao3402 2012-06-26 20:43
    关注

    You can use parse_url() to get the URL broken into parts, and then split the 'path' portion on the forward-slash character. That should allow you to re-assemble them and replace the last portion.

    Something like this (psuedo-code, untested, not sure it's even valid PHP syntax):

    $url_parts = parse_url($url_text);
    $path_parts = explode('/', $url_parts[path]);
    
    $new_url = $url_parts[scheme] + ":";
    
    if ($url_parts[scheme] == "file") {
        $new_url .= '///';
    } else {
        $new_url .= '//';
    }
    
    $new_url .= $url_parts[hostname] . '/';
    for (int i = 0; i < count($path_parts) - 1; i++) {
        $new_url .= $path_parts[i] . "/";
    } 
    
    $new_url .= $REPLACEMENT_FILENAME
    

    If need be, you can append the query string and/or anchor fragment (starts with #) at the end - see that parse_url() manual page for a list of the URL portions in its array.

    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)