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:

Read More
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.

Related posts

Leave a Reply

3 comments

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

  2. 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.
    }
    ?>
    
  3. 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.