Change a relative URL to absolute URL

前端 未结 3 1007
时光说笑
时光说笑 2020-12-16 06:36

for example i\'ve got a string like this:

$html = \'
            test
            

        
相关标签:
3条回答
  • 2020-12-16 07:03
    $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);
    }   
    
    0 讨论(0)
  • 2020-12-16 07:06

    found a good way :

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

    you can use (?!http|mailto) if you have also mailto links in your $html

    0 讨论(0)
  • 2020-12-16 07:08

    The previous answer will cause problems with your first and fourth example because it fails to include a forward slash to separate the page from the page name. Admittedly this can be fixed by simply appending it to the $domain, but if you do that then href="/something.php" will end up with two.

    Just to give an alternative Regex solution you could go with something like this...

    $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];
    }
    

    However it is worth noting that with a link such as href="example.html" the link is relative to the current directory neither method shown so far will work correctly for relative links that aren't in the root directory. In order to provide a solution that is though more information would be required about where the information came from.

    0 讨论(0)
提交回复
热议问题