Moritz Moritz -4 years ago 44
PHP Question

Extract specific part from URL

I have to extract a specific part of an URL.

Example

original URLs

http://www.example.com/PARTiNEED/some/other/stuff
http://www.example.com/PARTiNEED


in case 1 I need to extract

/PARTiNEED/


and in case 2 I need to extract the same part but add an additional "/" at the end

/PARTiNEED/


What I've got right now is this

$tempURL = 'http://'. $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$tempURL = explode('/', $tempURL);
$tempURL = "/" . $tempURL[3] . "/";


is there a more convenient way to do this or is this solution fine?

Answer Source

You don't need this part:

'http://'. $_SERVER['SERVER_NAME']

you can just do:

$tempURL = explode('/', $_SERVER['REQUEST_URI']);
$tempURL = "/" . $tempURL[1] . "/";

Edited index from 0 to 1 as commented.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download