2010-07-27 99 views
5

例如我有一个字符串,像这样:更改相对URL绝对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> 
     '; 

,我想绝对URL追加到没有abolute域给出所有的HREF。

$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技能是**;)

在此先感谢!

+0

虽然正则表达式可以让你去暂且可以在以后很危险时间点。最好将它解析为xml,检查属性是以“http://”开头,如果不是,则前置'http:// mydomain.com /'。 – Amarghosh 2010-07-27 11:05:11

+0

test应该被添加到示例中... – Hinek 2010-07-27 14:43:57

回答

9

找到了一个好办法:

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

你可以使用(?!http|mailto)如果你有同样的mailto在$ HTML链接

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); 
} 
+5

Romka,我为您设置了代码格式,以便我们在阅读时不会流血。 – 2010-07-27 13:14:10

1

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

只给一个替代的解决方案正则表达式,你可以像这样的东西去...

$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的”某条链路是相对的到目前的目录,到目前为止所显示的任何方法都不能正确地处理不在根目录中的相关链接。为了提供一个解决方案,尽管需要更多信息来说明信息的来源。