Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将相对URL更改为绝对URL_Php_Regex_Url_Hyperlink - Fatal编程技术网

Php 将相对URL更改为绝对URL

Php 将相对URL更改为绝对URL,php,regex,url,hyperlink,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="

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

$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>
        ';
$html='1!'
';
我想将绝对url附加到所有没有给定特定域的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>
        ';  
$html='1!'
';  
最好的方法是什么?我想是正则表达式的问题,但我的正则表达式技能是**;)


提前谢谢

前面的答案会给您的第一个和第四个示例带来问题,因为它没有包含一个正斜杠来分隔页面和页面名称。诚然,只需将其添加到$domain即可解决此问题,但如果这样做,href=“/something.php”将以两个结尾

$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);
}   
只是为了提供一个替代的正则表达式解决方案,你可以这样做

$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];
}
$pattern='#'#(?找到了一个好方法:

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

您可以使用
(?!http | mailto)
如果您的$html中也有mailto链接,尽管regex可能会让您暂时离开,但在以后的某个时候它可能会被证明是危险的。最好将其解析为xml,检查属性是否以
http://
和prepend
开头http://mydomain.com/
如果没有。应该添加到示例中…Romka,我格式化了您的为你编写代码,这样我们在阅读时眼睛就不会流血。