Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

How do I extract part of a URL? WordPress


I am passing a URL in the browser like

In my page template I am using

<?php echo $_SERVER['REQUEST_URI'];?>

to get the URL, which prints <strong>/Code/LT1234/</strong>

From here, how do I get ONLY "LT1234" I need it to put in a variable.


<em>Note: I cannot pass the link So I cant use GET to get the variable</em>


Answers (6)


Kailey Lampert answers:

This should work for what you describe above

$r = $_SERVER['REQUEST_URI']; // /Code/LT1234/

$r = explode('/', $r);
$r = array_filter($r);
$r = array_merge($r, array()); //reset keys
$code = $r[1];

But may require modification if you need more flexibility.

platinum comments:

Thank you this worked perfectly.


Maor Barazany answers:

If you need always to take the last part of the uri you got (i.e - <strong>/Code/LT1234/</strong>), than you can use php explode -

$tmp = explode('/', $uri);
$param = end($tmp);

echo $param;


Luis Cordova answers:

This should do, even better as you want to make sure you get the Code part in the url for security or error reporting purposes:


$urlPlusKey = $_SERVER['REQUEST_URI'];
$urlArray = explode('/', $urlPlusKey); // array(Code, LT1234)
$param = end($urlArray);
$codeIf = prev($urlArray);

if ($codeIf == 'Code') {
$key = $param;
} else {
$key = 'null';


The other approach with untrailingslashit is only wp based so be careful using that function
$url_part = untrailingslashit($url_parts['path']);
The other simplifications with basename online also could lack the security although it is simpler but will fail if your path does not contain the 'Code' string right before.


Jurre Hanema answers:

The single most simple way to do this in this case is the following one-liner:

$code = basename($_SERVER['REQUEST_URI']);



Luis Abarca answers:

$url = parse_url($_SERVER['REQUEST_URI']);

$path = explode('/', $url['path']);

// First element is a empty
$yourvar = array($path[1] => $path[2]);



Luke America answers:

one more example ...

$url_parts = parse_url($url);
$url_part = untrailingslashit($url_parts['path']);
$url_pieces = explode('/', $url_part);
$url_end_piece = end($url_pieces);