Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
967 views
in Technique[技术] by (71.8m points)

php - Extract part from URL for a query string

I need a certain part of a URL extracted.

Example:

http://www.domain.com/blog/entry-title/?standalone=1 is the given URL.

blog/entry-title should be extracted.

However, the extraction should also work with http://www.domain.com/index.php/blog/[…]as the given URL.

This code is for a Content Management System.


What I've already come up with is this:

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;

}

However, this code does not take care of the arguments at the end of the URL (like ?standalone=1). It works for anchors (#read-more), though.

Thanks a ton guys and have fun twisting your brains. Maybe we can do this shit with a regular expression.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's many examples and info for what you want at:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...