PHP:替换相对顶部URL”/";具有绝对域URL


PHP: replace relative top URL "../" with absolute domain URL

我想在RSS提要中将以../stuff/more.php开头的相对URL转换为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

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

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

此外,票据$2$3已更改为$3$4

编辑:

简化为一种替代方案:

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

为什么不将前2个点替换为域?

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

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

好吧,我将开始研究正则表达式。大部分看起来都很好(事实上,你在这里有一个足够好的正则表达式,我有点惊讶你在其他方面遇到了麻烦!)但结尾有点奇怪——最好是这样:

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

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

要删除../,我会完全脱离regex:

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";
}

(我为您提供了一个关于所需内容的小型测试套件-您只需要在里面标记代码即可。)

我找到了解决方案,这要归功于在这方面帮助我的每一个人。这是我使用的代码:

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

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