PHP:用绝对域URL替换相对顶部URL“../”

时间:2015-03-21 14:02:07

标签: php url preg-replace relative-url

我想在RSS Feed中将以../stuff/more.php开头的相对网址转换为http://www.example.com/stuff/more.php

我使用这个PHP代码是这样做的:

$content = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#", '$1http://www.example.com/$2$3', $content);

结果是错误的想法,它返回像这样的URL

http://www.example.com/../stuff/more.php

请注意../部分尚未删除,请提供帮助!

基本上......

这就是我所拥有的:../stuff/more.php

这是我得到的(在运行上面的代码之后):http://www.example.com/../stuff/more.php

这就是我想要的:http://www.example.com/stuff/more.php

5 个答案:

答案 0 :(得分:1)

添加(\。| \。\。| \ /)*应该有效。

$ content = preg_replace(&#34;#(&lt; \ s * a \ s + [^&gt;] href \ s = \ s * [\&#34;&#39 ])(?!HTTP)(../ | ../ | /)*([^ \&#34;&#39;&GT;] +)([\&#34;&#39;&GT; ] +)#&#34;,&#39; $ 1http://www.example.com/ $ 3 $ 4&#39;,$ content);

此外,请注意$ 2 $ 3已更改为$ 3 $ 4

编辑:

减少到一个替代方案:

    $content = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)(\.\.\/)*([^\"'>]+)([\"'>]+)#", '$1http://www.example.com/$3$4', $content);

答案 1 :(得分:0)

为什么不直接用域替换前2个点?

$result = str_replace('..', 'http://www.example.com', $contet, 1);

答案 2 :(得分:0)

使用$_SERVER[HTTP_HOST] $_SERVER[REQUEST_URI]是PHP中的全局变量来获取绝对URL。

答案 3 :(得分:0)

好吧,我会开始看正则表达式。大部分都看起来不错(事实上,你在这里得到了一个足够好的正则表达式,我很不高兴,否则你会遇到麻烦!)但最终有点奇怪 - 更像这样:

#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"']>)#

(从技术上讲,最好是捕捉起始报价,并确保它是匹配的结尾报价,但你很可能在那里遇到任何问题。

要删除../,我会完全从正则表达式中删除它:

foreach (array("<a href=\"http://../foo/bar\">", 
        "<a href=\"../foo/bar\">") as $content) {
    echo "A content=$content<br />\n";
    ########## copy from here down to...
    if (preg_match("#(<\s*a\s+[^>]*?href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"']>)#", $content, $m)) {
        echo "m=<pre>".print_r($m,true)."</pre><br />\n";
        if (substr($m[2], 0, 3) == '../')
            $m[2] = substr($m[2], 3);
        $content = $m[1].'http://www.example.com/'.$m[2].$m[3];
    }
    ######### copy from above down to HERE
    echo "B content=$content<br />\n";
}

(我在你正在寻找的内容中包含了一个迷你测试套件 - 你需要在代码中使用标记的线条。)

答案 4 :(得分:0)

我找到了解决方案,感谢所有帮助过我的人。 这是我使用的代码:

$content = preg_replace("#(<a href=\"\.\.\/)#", '<a href="http://www.example.com/', $content);

它会搜索<a href="../并将其替换为http://www.example.com/,但这不是一般性的,但这对我有用。