Get last word from URL after a slash in PHP - php

I need to get the very last word from an URL. So for example I have the following URL:
http://www.mydomainname.com/m/groups/view/test
I need to get with PHP only "test", nothing else. I tried to use something like this:
$words = explode(' ', $_SERVER['REQUEST_URI']);
$showword = trim($words[count($words) - 1], '/');
echo $showword;
It does not work for me. Can you help me please?
Thank you so much!!

Use basename with parse_url:
echo basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

by using regex:
preg_match("/[^\/]+$/", "http://www.mydomainname.com/m/groups/view/test", $matches);
$last_word = $matches[0]; // test

I used this:
$lastWord = substr($url, strrpos($url, '/') + 1);
Thnx to: https://stackoverflow.com/a/1361752/4189000

You can use explode but you need to use / as delimiter:
$segments = explode('/', $_SERVER['REQUEST_URI']);
Note that $_SERVER['REQUEST_URI'] can contain the query string if the current URI has one. In that case you should use parse_url before to only get the path:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
And to take trailing slashes into account, you can use rtrim to remove them before splitting it into its segments using explode. So:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', rtrim($_SERVER['REQUEST_URI_PATH'], '/'));

To do that you can use explode on your REQUEST_URI.I've made some simple function:
function getLast()
{
$requestUri = $_SERVER['REQUEST_URI'];
# Remove query string
$requestUri = trim(strstr($requestUri, '?', true), '/');
# Note that delimeter is '/'
$arr = explode('/', $requestUri);
$count = count($arr);
return $arr[$count - 1];
}
echo getLast();

If you don't mind a query string being included when present, then just use basename. You don't need to use parse_url as well.
$url = 'http://www.mydomainname.com/m/groups/view/test';
$showword = basename($url);
echo htmlspecialchars($showword);
When the $url variable is generated from user input or from $_SERVER['REQUEST_URI']; before using echo use htmlspecialchars or htmlentities, otherwise users could add html tags or run JavaScript on the webpage.

use preg*
if ( preg_match( "~/(.*?)$~msi", $_SERVER[ "REQUEST_URI" ], $vv ))
echo $vv[1];
else
echo "Nothing here";
this was just idea of code. It can be rewriten in function.
PS. Generally i use mod_rewrite to handle this... ans process in php the $_GET variables.
And this is good practice, IMHO

ex: $url = 'http://www.youtube.com/embed/ADU0QnQ4eDs';
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url_path = parse_url($url, PHP_URL_PATH);
$basename = pathinfo($url_path, PATHINFO_BASENAME);
// **output**: $basename is "ADU0QnQ4eDs"
complete solution you will get in the below link. i just found to Get last word from URL after a slash in PHP.
Get last parameter of url in php

Related

Remove all characters before last / in URL [duplicate]

This question already has answers here:
Get Last Part of URL PHP
(14 answers)
Closed 7 years ago.
I need to remove every characters before the last "/"
This my url :
http://www.example.com/highlights/cat/all-about-clothing/
And I want to have only :
all-about-clothing
Thanks
Use basename()
$str = 'http://www.example.com/highlights/cat/all-about-clothing/';
echo basename($str);
// Outputs: all-about-clothing
EDIT:
Another Solution:
$str = 'http://www.example.com/highlights/cat/all-about-clothing/';
$path = pathinfo($str, PATHINFO_BASENAME);
echo "<br/>" . $path;
Use PHP's parse_url() function.
edit:
basename() or pathinfo() is the easier way.
$str = 'http://www.example.com/highlights/cat/all-about-clothing/';
$str = trim($str,'/');
$str = explode('/',$str);
echo $str = end($str);
// get result
all-about-clothing
<?php
$url = "http://www.example.com/highlights/cat/all-about-clothing/";
$url_path = parse_url($url, PHP_URL_PATH);
$basename = pathinfo($url_path, PATHINFO_BASENAME);
echo $basename;
?>
You can use regex too:
$match = [];
$subject = 'http://www.example.com/highlights/cat/all-about-clothing/';
$pattern = '/http:\/\/www\.example\.com\/highlights\/cat\/(.*)/';
preg_match($pattern, $subject, $match);
print_r($match);
You can see the result here.
<?php
$url = 'http://www.example.com/highlights/cat/all-about-clothing/';
$basename = split('/',$url);
echo $basename[5];
?>
Most of the above solution focus on the exact example URL,
Please be careful as if extra params are added to the end of the string,
you may get the wrong result:
http://www.example.com/highlights/cat/all-about-clothing/?page=1
http://www.example.com/highlights/cat/all-about-clothing/item/1
to cache the 3rd "directory" after the domain name, and ignore the rest of the URL, the following code can be used:
$url = "http://www.example.com/highlights/cat/all-about-clothing/item/1";
$url_path = parse_url($url, PHP_URL_PATH); # /highlights/cat/all-about-clothing/item/1
$dirs = explode('/', $url_path); # Array([0] =>"", [1]=>"highlights", [2]=>"cat", [3]=>"all-about-clothing", [4]=>"item", [5]=>"1")
echo $dirs[3]; # all-about-clothing

parse_url and removing subdomain

I'm wanting to strip out everything from a URL but the domain. So http://i.imgur.com/rA81kQf.jpg becomes imgur.com.
$url = 'http://i.imgur.com/rA81kQf.jpg';
$parsedurl = parse_url($url);
$parsedurl = preg_replace('#^www\.(.+\.)#i', '$1', $parsedurl['host']);
// now if a dot exists, grab everything after it. This removes any potential subdomain
$parsedurl = preg_replace("/^(.*?)\.(.*)$/","$2",$parsedurl);
The above works but I feel like I should only being one preg_replace for this. Any idea how I may combine the two?
You can use parse_url() to get desired output like this,
$url = "http://i.imgur.com/rA81kQf.jpg";
$parseData = parse_url($url);
$domain = preg_replace('/^www\./', '', $parseData['host']);
$array = explode(".", $domain);
echo (array_key_exists(count($array) - 2, $array) ? $array[count($array) - 2] : "") . "." . $array[count($array) - 1];
which prints
imgur.com

Get the first directory from URL with PHP

I have url in variable like this:
$url = 'http://mydomain.com/yep/2014-04-01/some-title';
Then what I want is to to parse the 'yep' part from it. I try it like this:
$url_folder = strpos(substr($url,1), "/"));
But it returns some number for some reason. What I do wrong?
Use explode, Try this:
$url = 'http://mydomain.com/yep/2014-04-01/some-title';
$urlParts = explode('/', str_ireplace(array('http://', 'https://'), '', $url));
echo $urlParts[1];
Demo Link
Well, first of all the substr(...,1) will return to you everthing after position 1. So that's not what you want to do.
So http://mydomain.com/yep/2014-04-01/some-title becomes ttp://mydomain.com/yep/2014-04-01/some-title
Then you are doing strpos on everthing after position 1 , looking for the first / ... (Which will be the first / in ttp://mydomain.com/yep/2014-04-01/some-title). The function strpos() will return you the position (number) of it. So it is returning you the number 4.
Rather you use explode():
$parts = explode('/', $url);
echo $parts[3]; // yep
// $parts[0] = "http:"
// $parts[1] = ""
// $parts[2] = "mydomain.com"
// $parts[3] = "yep"
// $parts[4] = "2014-04-01"
// $parts[4] = "some-title"
The most efficient solution is the strtok function:
strtok($path, '/')
So complete code would be :
$dir = strtok(parse_url($url, PHP_URL_PATH), '/')
Use parse_url function.
$url = 'http://mydomain.com/yep/2014-04-01/some-title';
$url_array = parse_url($url);
preg_match('#/(?<path>[^/]+)#', $url_array['path'], $m);
$url_folder = $m['path'];
echo $url_folder;

Get the filename part from a given URL

I have a URL like below:
http://abc.def.com/gh-tqa/name-of-the-file/ZW607CCF.html
Now I want to get the string of ZW607CCF without .html.
How can I achieve this using PHP?
You don't need a regex here. Just use pathinfo():
$url = 'http://abc.def.com/gh-tqa/name-of-the-file/ZW607CCF.html';
$filename = pathinfo($url, PATHINFO_FILENAME);
There are lot of ways in PHP, try preg_replace(), for example:
$url = 'http://abc.def.com/gh-tqa/name-of-the-file/ZW607CCF.html';
$value = preg_replace("|.*/([^.]+)\.html|", "$1", $url);
this is how you do:
$temp = explode('.', $_SERVER['PHP_SELF']);
$string = $temp[0];
with PHP 5.4+ you can also do:
$string = explode('.', $_SERVER['PHP_SELF'])[0];

URL - Get last part in PHP

I have my url:
http://domain/fotografo/admin/gallery_bg.php
and i want last part of the url:
gallery_bg.php
but, I do not want to link static, ie, for each page that vistitar I want to get the last part of the url
use following
<?php
$link = $_SERVER['PHP_SELF'];
$link_array = explode('/',$link);
echo $page = end($link_array);
?>
Use basename function
echo basename("http://domain/fotografo/admin/gallery_bg.php");
If it is same page:
echo $_SERVER["REQUEST_URI"];
or
echo $_SERVER["SCRIPT_NAME"];
or
echo $_SERVER["PHP_SELF"];
In each case a back slash(/gallery_bg.php) will appear. You can trim it as
echo trim($_SERVER["REQUEST_URI"],"/");
or split the url by / to make an array and get the last item from array
$array = explode("/",$url);
$last_item_index = count($url) - 1;
echo $array[$last_item_index];
or
echo basename($url);
$url = "http://domain/fotografo/admin/gallery_bg.php";
$keys = parse_url($url); // parse the url
$path = explode("/", $keys['path']); // splitting the path
$last = end($path); // get the value of the last element
you can use basename($url) function as suggested above. This returns the file name from the url. You can also provide the file extension as second argument to this function like basename($url, '.jpg'), then the filename without the extension will be served.
Eg:
$url = "https://i0.com/images/test.jpg"
then echo basename($url) will print test.jpg
and echo basename($url,".jpg") will print test
$url = $_SERVER["PHP_SELF"];
$path = explode("/", $url);
$last = end($path);
Try this:
Here you have 2 options.
1. Using explode function.
$filename = end(explode('/', 'http://domain/fotografo/admin/gallery_bg.php'));
2. Use basename function.
$filename = basename("http://domain/fotografo/admin/gallery_bg.php");
-
Thanks
$basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
$uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
if (strstr($uri, '?')) $uri = substr($uri, 0, strpos($uri, '?'));
$url = trim($uri, '/');
In PHP 7 the accepted solution is giving me the error that only variables are allowed in explode so this works for me.

Categories