从URL中提取部分以查询查询字符串

时间:2010-06-20 18:56:07

标签: php regex

我需要提取网址的某个部分。

示例:

http://www.domain.com/blog/entry-title/?standalone=1是给定的网址。

应该提取

blog/entry-title

但是,提取也应该与http://www.domain.com/index.php/blog/[…]一起用作给定的URL。

此代码适用于内容管理系统。


我已经提出的是:

function getPathUrl() {

    $folder = explode('/', $_SERVER['SCRIPT_NAME']);
    $script_filename = pathinfo($_SERVER['SCRIPT_NAME']); // supposed to be 'index.php'
    $request = explode('/', $_SERVER['REQUEST_URI']);

    // first element is always ""
    array_shift($folder);
    array_shift($request);

    // now it's only the request url. filtered out containing folders and 'index.php'.
    $final_request = array_diff($request, array_intersect($folder, $request));

    // the indexes are mangled up in a strange way. turn 'em back
    $final_request = array_values($final_request);

    // remove empty elements in array (caused by superfluent slashes, for instance)
    array_clean($final_request);

    // make a string out of the array
    $final_request = implode('/', $final_request);

    if ($_SERVER['QUERY_STRING'] || substr($final_request, -1) == '?') {
        $final_request = substr($final_request, 0, - strlen($_SERVER['QUERY_STRING']) - 1);
    }

    return $final_request;

}

但是,此代码不会处理URL末尾的参数(如?standalone=1)。但它适用于锚点(#read-more)。

非常感谢大家,玩得开心扭曲你的大脑。也许我们可以用正则表达式来做这件事。

2 个答案:

答案 0 :(得分:1)

您需要的内容有很多示例和信息:

http://php.net/manual/en/function.parse-url.php

答案 1 :(得分:1)

那应该做你需要的:

<?php
function getPath($url)
{
$path = parse_url($url,PHP_URL_PATH);
$lastSlash = strrpos($path,"/");
return substr($path,1,$lastSlash-1);
}

echo getPath("http://www.domain.com/blog/entry-title/?standalone=1");

?>
相关问题