1

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.

Daniel
  • 4,949
  • 4
  • 34
  • 50

2 Answers2

2

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

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

Zuul
  • 16,217
  • 6
  • 61
  • 88
  • I forgot to mention that the index.php may be in a physical directory, such as `http://www.domain.com/cms/`. My code works so far and through the `parse_url` function you referred me to it now also ignores the additional arguments of the query string. Cheers buddy! – Daniel Jun 20 '10 at 19:36
1

That should do what you need:

<?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");

?>
OdinX
  • 4,135
  • 1
  • 24
  • 33
  • Thank you, I've already taken care of the "trailing" slash of the URL. You will find my final solution described above in a comment on @Zuul's answer. – Daniel Jun 20 '10 at 19:38