0

我正在努力弄清楚如何做到这一点。我有一个 HTML 页面的绝对 URL,我需要为此获取基本 URL。因此 URL 可以是例如:

等等。因此,第一个问题是从这些 URL 和其他 URL 中找到基本 URL。第二个问题是一些 HTML 页面包含一个基本标签,例如,它可能是http://example.com/或简单的/(尽管我认为某些浏览器只支持以protocol://? 开头的标签)。

无论哪种方式,我怎样才能在 PHP 中正确地做到这一点?我有 URL,并且我在 DOMDocument 中加载了 HTML,因此如果存在基本标记,应该能够相当容易地获取它。例如,浏览器如何解决这个问题?


澄清为什么我需要这个

我正在尝试创建一个将 URL 指向网页并将绝对 URL 返回到该网页链接到的所有图像的东西。由于某些/许多/所有这些图像可能具有相对 URL,因此我需要找到要在使它们成为绝对 URL 时使用的基本 URL。这可能是网页的基本 URL,也可能是 HTML 本身中指定的基本 URL。

我设法获取 HTML 并找到 URL。我想我还找到了一种在我有要使用的基本 URL 时使 URL 成为绝对的工作方法。但是找到基本 URL 是我所缺少的,也是我在这里要问的。

4

2 回答 2

4

parse_url()

$result=parse_url('http://www.google.com');
print_r($result);

从那里挑选您正在寻找的任何元素。你可能想要$result['path'].

于 2011-04-14T15:10:38.437 回答
0

片段的乐趣!

if (!function_exists('base_url')) {
    function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){
        if (isset($_SERVER['HTTP_HOST'])) {
            $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
            $hostname = $_SERVER['HTTP_HOST'];
            $dir =  str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);

            $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
            $core = $core[0];

            $tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
            $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
            $base_url = sprintf( $tmplt, $http, $hostname, $end );
        }
        else $base_url = 'http://localhost/';

        if ($parse) {
            $base_url = parse_url($base_url);
            if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
        }

        return $base_url;
    }
}

使用简单:

//  url like: http://stackoverflow.com/questions/2820723/how-to-get-base-url-with-php

echo base_url();    //  will produce something like: http://stackoverflow.com/questions/2820723/
echo base_url(TRUE);    //  will produce something like: http://stackoverflow.com/
echo base_url(TRUE, TRUE); || echo base_url(NULL, TRUE);    //  will produce something like: http://stackoverflow.com/questions/
//  and finally
echo base_url(NULL, NULL, TRUE);
//  will produce something like: 
//      array(3) {
//          ["scheme"]=>
//          string(4) "http"
//          ["host"]=>
//          string(12) "stackoverflow.com"
//          ["path"]=>
//          string(35) "/questions/2820723/"
//      }
于 2013-11-21T18:50:02.007 回答