I'm creating a gallery in wordpress and I am attempting to grab a particular a part of my hyperlink to echo in to the id of the div.

This really is my url: http://www.url.com/gallery/truck-gallery-1

I wish to isolate the id from the gallery which will be several(within this situation its 1). Then I must have the means to print it somewhere, maybe as a funtion.

Interesting help

Make use of the $_SERVER['REQUEST_URI'] variable to obtain the path (Observe that this really is different then the host variable, which returns something similar to http://www.yoursite.com).

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

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

Obviously you can do other kinds of string manipulation to obtain the final character of the string. But this works.

You need to better use $_SERVER['REQUEST_URI']. As it is the final string inside your URL, you should use the next function:

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

@Kristian 's solution is only going to return amounts from -9, but this function will return the id with any length given, as lengthy as the ID is separated having a - sign and also the last element.

So, whenever you call

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

it'll echo, inside your situation, 1.

When the ID won't continually be exactly the same quantity of numbers (for those who have any ID's more than 9) then you will want something robust like preg_match() or using string functions to trim off everything just before the final "-" character. I'd most likely do:

$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.