开发者

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 func开发者_高级运维tion.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜