php subdomain.domain假定为str_replace上的扩展名

I am trying to strip filename.extension from my local domain

local domain virtual host: http://cms.local/

and on str_replace I am trying to remove index.php to keep it dynamic my main concern is to consider the fact that filename.extension could be anything.

my code to do so:

private static function removeFilename($url) { $file_info = pathinfo($url); return isset($file_info['extension']) ? str_replace($file_info['filename'] . "." . $file_info['extension'], "", $url) : $url; }

where $url is unparsed url based on this post.

Considering that my url is http://cms.local/index.php everything is going smoothly but in case my url is just http://cms.local/; without filename.extension, str_replace function removes cms.local as if it is the filename.extension, leaving just http:///.

Thanks you in advance!

private static function removeFilename($url) {
    return substr($url, 0, strrpos($url, '/') + 1);
}

substr() Returns the portion of string specified by the start and length parameters.

strrpos() Find the numeric position of the last occurrence of needle in the haystack string.

This will not work if url is http://cms.local without the last slash.

EDIT

If you need to keep query string and remove just filename + extension:

function removeFilename($url) {
    $queryString = parse_url($url, PHP_URL_QUERY);
    return substr($url, 0, strrpos($url, '/') + 1) . "?" . $queryString;
}

parse_url() function parses a URL and returns an associative array containing any of the various components of the URL that are present. The values of the array elements are not URL decoded.

component

Specify one of PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT to retrieve just a specific URL component as a string (except when PHP_URL_PORT is given, in which case the return value will be an integer).

EDIT 2 Final solution with adding a trailing slash if url is http://cms.local

private static function addTrailingSlash($url) {
    $url = parse_url($url);
    if(!isset($url['path'])) $url['path'] = '/';
    $surl = $url['scheme']."://".$url['host'].$url['path'].'?'.$url['query'];
    return $surl;   
}

private static function removeFilename($url) {
    $url = addTrailingSlash($url);
    $queryString = parse_url($url, PHP_URL_QUERY);
    return substr($url, 0, strrpos($url, '/') + 1) . "?" . $queryString;
}