有时候我们需要采集内容,有些网页上面显示的是相对地址,这时候我们需要一个方法来格式化这些网址,让这些相对网址都转为带域名的绝对网址
/**
* 网址补全
* @param string $url 访问的网址
* @param string $str 需要格式化的相对地址
* @return array|mixed|string
*/
function formaturl($url, $str)
{
if (stripos($str, 'http://') === 0 || stripos($str, 'ftp://') === 0) {
return $str;
}
$str = str_replace('\\', '/', $str);
$parseUrl = parse_url(dirname($url) . '/');
$scheme = isset($parseUrl['scheme']) ? $parseUrl['scheme'] : 'http';
$host = $parseUrl['host'];
$path = isset($parseUrl['path']) ? $parseUrl['path'] : '';
$port = isset($parseUrl['port']) ? $parseUrl['port'] : '';
if (strpos($str, '/') === 0) {
return $scheme . '://' . $host . $str;
} else {
$part = explode('/', $path);
array_shift($part);
$count = substr_count($str, '../');
if ($count > 0) {
for ($i = 0; $i <= $count; $i++) {
array_pop($part);
}
}
$path = implode('/', $part);
$str = str_replace(array('../', './'), '', $str);
$path = $path == '' ? '/' : '/' . trim($path, '/') . '/';
return $scheme . '://' . $host . $path . $str;
}
}
