简体   繁体   中英

Change all relative URLs in an array to absolute URLs

I have an array that contains some relative URLs ( file.html ) and absolute URLs ( http://website.com/index.html ).

I am trying to convert them into absolute URLs.

So, what I do is run through the array and check if the URL is absolute. If it is, then I add it to a new array of only absolute URLs.

If it is not an absolute URL, I take the the domain name from the current URL and concatenate that to the relative URL; thus, making it an absolute URL and then I add it to the array of only absolute URLs.

But, when I ran through the array of absolute URLs, I noticed some relative URLs.

What am I doing wrong?

foreach($anchors as $anchor){
    if(preg_match('/(?:https?:\/\/|www)[^\'\" ]*/i', (string)($anchor))){
        //has absolute URL
       //add to array
       array_push($matchList, (string)($anchor));
    }
    else{
        //has relative URL
        //change to absolute
        //add to array
        $urlPrefix = preg_match('/(?:https?:\/\/|www)[^\/]*/i', $url);
        $absolute = (string)(((string)$urlPrefix).((string)($anchor)));
        array_push($matchList, $absolute);
    }
}

This is not how preg_match() works (it does not return what it matchs, it returns either 0 when nothing match or 1 if a match occurs) :

$urlPrefix = preg_match('/(?:https?:\/\/|www)[^\/]*/i', $url);

you need to do like this :

preg_match('/(?:https?:\/\/|www)[^\/]*/i', $url, $matches);

urlPrefix  = $matches[0];

see preg_match()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM