将相对URL更改为绝对URL

时间:2010-07-27 10:45:19

标签: php regex url hyperlink

例如我有一个这样的字符串:

$html = '
            <a href="test.html">test</a>
            <a href="http://mydomain.com/test.html">test</a>
            <a href="http://otherdomain.com/test.html">test</a>
            <a href="someothertest/otherdir/hi.html">hi</a>
        ';

我希望将绝对网址附加到没有给出绝对域名的所有hrefs。

$html = '
            <a href="http://mydomain.com/test.html">test</a>
            <a href="http://mydomain.com/test.html">test</a>
            <a href="http://otherdomain.com/test.html">test</a>
            <a href="http://mydomain.com/someothertest/otherdir/hi.html">hi</a>
        ';  

最好的办法是什么?我猜RegEx的东西,但我的RegEx技能是**;)

提前感谢!

3 个答案:

答案 0 :(得分:9)

找到了一个好方法:

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

如果您的$ html

中还有mailto链接,则可以使用(?!http|mailto)

答案 1 :(得分:4)

$domain = 'http://mydomain';
preg_match_all('/href\="(.*?)"/im', $html, $matches);
foreach($matches[1] as $n=>$link) {
    if(substr($link, 0, 4) != 'http')
        $html = str_replace($matches[1][$n], $domain . $matches[1][$n], $html);
}   

答案 2 :(得分:1)

上一个答案将导致您的第一个和第四个示例出现问题,因为它无法包含正斜杠以将页面与页面名称分开。不可否认,这可以通过简单地将其附加到$ domain来修复,但如果你这样做,那么href =“/ something.php”最终会有两个。

只是提供一个替代的Regex解决方案,你可以使用这样的东西......

$pattern = '#'#(?<=href=")(.+?)(?=")#'';
$output = preg_replace_callback($pattern, 'make_absolute', $input);

function make_absolute($link) {
    $domain = 'http://domain.com';
    if(strpos($link[1], 'http')!==0) {
        if(strpos($link[1], '/')!==0) {
            return $domain.'/'.$link[1];
        } else {
            return $domain.$link[1];
        }
    }
    return $link[1];
}

但是值得注意的是,使用诸如href =“example.html”之类的链接,链接相对于当前目录,到目前为止所示的方法都不能正常用于不在根目录中的相对链接。为了提供解决方案,尽管需要更多关于信息来源的信息。

相关问题