【问题标题】:Change all relative URLs in an array to absolute URLs将数组中的所有相对 URL 更改为绝对 URL
【发布时间】:2013-04-10 15:57:56
【问题描述】:

我有一个包含一些相对 URL (file.html) 和绝对 URL (http://website.com/index.html) 的数组。

我正在尝试将它们转换为绝对 URL。

所以,我要做的是遍历数组并检查 URL 是否是绝对的。如果是,那么我将其添加到仅包含绝对 URL 的新数组中。

如果不是绝对 URL,我会从当前 URL 中获取域名并将其连接到相对 URL;因此,将其设为绝对 URL,然后将其添加到仅包含绝对 URL 的数组中。

但是,当我浏览绝对 URL 数组时,我注意到了一些相对 URL。

我做错了什么?

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

【问题讨论】:

标签: php regex


【解决方案1】:

这不是 preg_match() 的工作方式(它不返回匹配的内容,如果没有匹配则返回 0,如果匹配则返回 1):

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

你需要这样做:

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

urlPrefix  = $matches[0];

preg_match()

【讨论】:

  • 啊,好吧。非常感谢您的解释。
猜你喜欢
  • 1970-01-01
  • 2018-07-27
  • 2011-01-08
  • 2011-11-24
  • 1970-01-01
  • 2014-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多