2013-10-27 73 views
1

输入:转换相对URL绝对URL

  • 基地网址:www.example.com/1/2/index.php
  • 相对URL:../../index.php

输出:

  • 绝对URL:www.example.com/index.php

这将是完美的,它将使用sed完成。

据我所知,该正则表达式应该在URL中每../删除一个somefolder/

+0

这几乎是dublicate的http://stackoverflow.com/questions/4444475/transfrom-relative-path-into-absolute-url-using-php – qdinar

回答

-4

对此,您无法使用单个正则表达式,因为正则表达式无法计数。

您应该使用真正的编程语言。即使Java可以轻松做到这一点。

0

如果您的唯一要求是将..变成“上一级”,那么这是一个可能的解决方案。它不使用正则表达式或sed或为此事JVM)

#!/bin/bash                                 

domain="www.example.com" 
origin="1/2/3/4/index.php" 
rel="../../index.php" 

awk -v rel=$rel -v origin=$origin -v file=$(basename $rel) -v dom=$domain '                 
BEGIN {                                  
    n = split(rel, a, "/")                             
    for(i = 1; i <= n; ++i) {                            
     if(a[i] == "..") ++c                            
    }                                  
    abs = dom                                
    m=split(origin, b, "/")                             
    for(i = 1; i < m - c; ++i) {                           
     abs=abs"/"b[i]                              
    }                                  
    print abs"/"file                              
}' 

的另一种方法使用awk,信贷爱德华的提realpath -m

#!/bin/bash                                 

rel="../../index.php" 
origin="www.example.com/1/2/index.php" 

directory=$(dirname $origin) 
fullpath=$(realpath -m "$directory/$rel") 
echo ${fullpath#$(pwd)/} 
0

realpath是一个快速但有点做事做你想做的事。
(事实上,我很惊讶,它不使用URL妥善处理,而是把他们当作普通的旧文件系统路径。)
~$ realpath -m http://www.example.com/1/2/../../index.php => ~$ /home/username/http:/www.example.com/index.php
-m(对于“失踪”)称,以解决即使它的组件实际上不存在于文件系统中也是如此。
所以你仍然必须剥离实际的文件系统部分(这将只是$(pwd)。注意,协议的斜杠也被标准化为一个斜线,所以你最好离开输入“http://”关闭您输入的,只是它前面加上你的输出,而不是
了更详细的全文看man 1 realpath完整故事或者info coreutils 'realpath invocation',如果您已经安装了信息系统

0

。在bash内使用sed

#!/bin/bash 

base_url='www.example.com/1/2/index.php' 
rel_url='../../index.php' 

str="${base_url};${rel_url}" 
str=$(echo $str | sed -r 's#/[^/]*;#/#') 
while [ ! -z $(echo $str | grep '\.\.') ] 
do 
    str=$(echo $str | sed -r 's#\w+/\.\./##') 
done 
abs_url=$str 

echo $abs_url 

输出:

www.example.com/index.php