[英]Change a relative URL to absolute URL
例如,我有一个像这样的字符串:
$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技能是**;)
提前致谢!
找到了一个好方法:
$html = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#", '$1http://mydomain.com/$2$3', $html);
如果你的$ html中还有mailto链接,你可以使用(?!http|mailto)
$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);
}
上一个答案将导致您的第一个和第四个示例出现问题,因为它无法包含正斜杠以将页面与页面名称分开。 不可否认,这可以通过简单地将其附加到$ 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”之类的链接,链接相对于当前目录,到目前为止所示的方法都不能正确地用于不在根目录中的相对链接。 为了提供解决方案,尽管需要更多关于信息来源的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.