How to Get Part of Url Before Last Slash With PHP

How to get string before last slash and after second last slash in URL

$str = explode("/","http://wwww.example/test1/test2/test3/");
echo $str[count($str)-2];


Get End Part of URL Before Trailing Slash

This works for me

$link = $_SERVER["REQUEST_URI"];
if(substr($link, -1) == '/') {
$link = substr($link, 0, -1);
$link_array = explode('/',$link);
echo $page = strtoupper(end($link_array));

Get characters after last / in url

Very simply:

$id = substr($url, strrpos($url, '/') + 1);

strrpos gets the position of the last occurrence of the slash; substr returns everything after that position.

As mentioned by redanimalwar if there is no slash this doesn't work correctly since strrpos returns false. Here's a more robust version:

$pos = strrpos($url, '/');
$id = $pos === false ? $url : substr($url, $pos + 1);

Get the value of a URL after the last slash

As easy as:

substr(strrchr(rtrim($url, '/'), '/'), 1)

Get Last Part of URL PHP

You can use preg_match to match the part of the URL that you want.

In this case, since the pattern is easy, we're looking for a forward slash (\/ and we have to escape it since the forward slash denotes the beginning and end of the regular expression pattern), along with one or more digits (\d+) at the very end of the string ($). The parentheses around the \d+ are used for capturing the piece that we want: namely the end. We then assign the ending that we want ($end) to $matches[1] (not $matches[0], since that is the same as $url (ie the entire string)).


//Your URL didn't match. This may or may not be a bad thing.

Note: You may or may not want to add some more sophistication to this regular expression. For example, if you know that your URL strings will always start with http:// then the regex can become /^http:\/\/.*\/(\d+)$/ (where .* means zero or more characters (that aren't the newline character)).

Remove all characters before last / in URL

Use basename()

$str = '';
echo basename($str);
// Outputs: all-about-clothing


Another Solution:

$str = '';
$path = pathinfo($str, PATHINFO_BASENAME);
echo "<br/>" . $path;

Get last word from URL after a slash in PHP

by using regex:

preg_match("/[^\/]+$/", "", $matches);
$last_word = $matches[0]; // test

php: Insert string before last slash in url

There are a lot of ways. Try using URL and path functions and replacing:

$string = str_replace($dir=dirname(parse_url($string, PHP_URL_PATH)),

Or string functions:

$string = str_replace($s=strrchr($string, '/'), "/thumbs$s", $string);

Related Topics

Leave a reply