Carlos Rios
Carlos Rios

Reputation: 345

Isolate part of url with php and then print it in html element

I am building a gallery in WordPress and I'm trying to grab a specific part of my URL to echo into the id of a div.

This is my URL:

http://www.url.com/gallery/truck-gallery-1

I want to isolate the id of the gallery which will always be a number(in this case its 1). Then I would like to have a way to print it somewhere, maybe in the form of a function.

Upvotes: 2

Views: 1125

Answers (3)

Sascha Galley
Sascha Galley

Reputation: 16091

You should better use $_SERVER['REQUEST_URI']. Since it is the last string in your URL, you can use the following function:

function getIdFromUrl($url) {
    return str_replace('/', '', array_pop(explode('-', $url)));
}

@Kristian 's solution will only return numbers from 0-9, but this function will return the id with any length given, as long as your ID is separated with a - sign and the last element.

So, when you call

 echo getIdFromUrl($_SERVER['REQUEST_URI']);

it will echo, in your case, 1.

Upvotes: 2

Kristian
Kristian

Reputation: 21840

Use the $_SERVER['REQUEST_URI'] variable to get the path (Note that this is not the same as the host variable, which returns something like http://www.yoursite.com).

Then break that up into a string and return the final character.

$path = $_SERVER['REQUEST_URI'];
$ID   = $path[strlen($path)-1];

Of course you can do other types of string manipulation to get the final character of a string. But this works.

Upvotes: 0

curtisdf
curtisdf

Reputation: 4210

If the ID will not always be the same number of digits (if you have any ID's greater than 9) then you'll need something robust like preg_match() or using string functions to trim off everything prior to the last "-" character. I would probably do:

<?php
$parts = parse_url($_SERVER['REQUEST_URI']);
if (preg_match("/truck-gallery-(\d+)/", $parts['path'], $match)) {
    $id = $match[1];
} else {
    // no ID found!  Error handling or recovery here.
}
?>

Upvotes: 1

Related Questions