将相对URL更改为绝对URL

cho*_*ise 5 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>
        ';
Run Code Online (Sandbox Code Playgroud)

我想将绝对网址附加到没有给出绝对域名的所有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>
        ';  
Run Code Online (Sandbox Code Playgroud)

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

提前致谢!

cho*_*ise 9

找到了一个好方法:

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

(?!http|mailto)如果你的$ html中还有mailto链接,你可以使用