I have the following URI:
/belt/belts/fk/product/40P35871
And I want to retrieve the last content after the last /.
In this case is 40P35871.
How can I do this?
How about explode?
$elements = explode('/', $input);
$productId = end($elements);
Here's a different solution entirely. (and the simplest!)
Using basename
$var = "/belt/belts/fk/product/40P35871";
echo basename($var);
Output:
40P35871
You don't need regex for something simple like that. Consider using strrchr, documentation here
$lastcontent = substr(strrchr($uri, "/"), 1);
Considering this special case of $uri being a path, the best answer would be the one provided by Chtulhu.
basename will return the last part of a path, documentation here
$lastcontent = basename($uri);
Just like this
$str = '/belt/belts/fk/product/40P35871';
$arr = explode('/', $str);
$var = array_pop($arr);
var_dump($var);
or
$var = substr($str, strrpos($str,'/') + 1);
Try this
$result = preg_replace('%(/(?:[^/]+?/)+)([^/]+)\b%', '$2', $subject);
use this:
echo preg_replace('/[a-z0-9]$/i', '$1', $url);
this will give you the last position
note: but on this url only, query strings make this useless and use need to parse the url for the same first for this to work
Don't use regex. In this case you can act as the follow
myUrl = $_SERVER[REQUEST_URL];
$number = substr(strrpos(myUri,'/')+1);
You don't need regex.
Find the last content and get it using substr():
$lastcontent = substr(strrchr($uri, "/"), 1);
Related
I have this string:
"application/controllers/backend"
I want get:
backend
of course the backend it's dynamic, so could be change, so I'm looking for a solution that allow me to get only the last part of the string. How I can do that?
You can take the advantage of basename() to get the last part
in your case, it will be
basename("application/controllers/backend");
Output:
backend
Some thing like this :
echo end(explode("/", $url));
If this thorws error then do :
$parts = explode("/", $url);
echo end($parts);
$arr = explode ("/", $string);
//$arr[2] is your third element in the string
http://php.net/manual/en/function.explode.php
Just use
basename("application/controllers/backend");
http://php.net/manual/en/function.basename.php
And, if you want to do it with a regex:
$result = (preg_match('%.*[/\\\\](.*?)$%', $url, $regs)) ? $regs[1] : '';
You did ask initially for a solution with regex, so, although the other answers haven't involved regex, here is one approach which does.
You can use preg_match and str_replace for this:
$string = '"application/controllers/backend"';
preg_match('/[^\/]+"/', $string, $matches);
$last_item = str_replace('"','',$matches[0]);
$last_item is now a string containing the word backend.
I have looked around for this but can only find links and references to this been done after an anchor hashtag but I need to get the value of the URL after the last / sign.
I have seen this used like this:
www.somesite.com/archive/some-post-or-article/53272
the last bit 53272 is a reference to an affiliate ID..
Thanks in advance folks.
PHPs parse_url (which extracts the path from the URL) combined with basename (which returns the last part) will solve this:
var_dump(basename(parse_url('http://www.somesite.com/archive/some-post-or-article/53272', PHP_URL_PATH)));
string(5) "53272"
You can do this :
$url = 'www.somesite.com/archive/some-post-or-article/53272';
$id = substr(url, strrpos(url, '/') + 1);
You can do it in one line with explode() and array_pop() :
$url = 'www.somesite.com/archive/some-post-or-article/53272';
echo array_pop(explode('/',$url)); //echoes 53272
<?php
$url = "www.somesite.com/archive/some-post-or-article/53272";
$last = end(explode("/",$url));
echo $last;
?>
Use this.
I'm not an expert in PHP, but I would go for using the split function: http://php.net/manual/en/function.split.php
Use it to split a String representation of your URL with the '/' pattern, and it will return you an array of strings. You will be looking for the last element in the array.
This will work!
$url = 'www.somesite.com/archive/some-post-or-article/53272';
$pieces = explode("/", $url);
$id = $pieces[count($pieces)]; //or $id = $pieces[count($pieces) - 1];
If you always have the id on the same place, and the actual link looks something like
http://www.somesite.com/archive/article-post-id/74355
$link = "http://www.somesite.com/archive/article-post-id/74355";
$string = explode('article-post-id/', $link);
$string[1]; // This is your id of the article :)
Hope it helped :)
$info = parse_url($yourUrl);
$result = '';
if( !empty($info['path']) )
{
$result = end(explode('/', $info['path']));
}
return $result;
$url = 'www.somesite.com/archive/some-post-or-article/53272';
$parse = explode('/',$url);
$count = count($parse);
$yourValue = $parse[$count-1];
That's all.
I'm trying to do some string matching in PHP. I have the following url string in a variable:
phones/gift.nintendo-3ds/handset.blackberry-9790.html
I want remove the /gift.nintendo-3ds from the above, but the gift will always be different.
Any ideas? I want the url variable to look like this after each call different gifts:
phones/handset.blackberry-9790.html
Thanks
preg_replace('/\/gift\.[^/]*/', '', $url);
Matches /gift. then anything till the next slash and replaces it with blank.
Try with:
$input = 'phones/gift.nintendo-3ds/handset.blackberry-9790.html';
$output = preg_replace('(gift\.[^/]*\/)', '', $input);
You could split it apart, remove the second part you do not want to keep and then concat it again:
$parts = explode('/', $url, 3);
unset($parts[1]);
$result = implode('/', $parts);
This is not using any regular expression as you might have thought about but probably tells you about some other useful functions.
Demo: http://codepad.org/a1pNW8J6
A regex variant could be:
echo preg_replace('~^([^/]+)(/[^/]+)~', '$1', $url);
Demo: http://codepad.org/vyR04xMn
i have this URI.
http://localhost/index.php?properties&status=av&page=1
i am fetching basename of the URI using following code.
$basename = basename($_SERVER['REQUEST_URI']);
the above code gives me following string.
index.php?properties&status=av&page=1
i would want to remove the last variable from the string i.e &page=1. please note the value for page will not always be 1. keeping this in mind i would want to trim the variable this way.
Trim from the last position of the string till the first delimiter i.e &
Update :
I would like to remove &page=1 from the string, no matter in which position it is on.
how do i do this?
Instead of hacking around with regular expression you should parse the string as an url (what it is)
$string = 'index.php?properties&status=av&page=1';
$parts = parse_url($string);
$queryParams = array();
parse_str($parts['query'], $queryParams);
Now just remove the parameter
unset($queryParams['page']);
and rebuild the url
$queryString = http_build_query($queryParams);
$url = $parts['path'] . '?' . $queryString;
There are many roads that lead to Rome. I'd do it with a RegEx:
$myString = 'index.php?properties&status=av&page=1';
$myNewString = preg_replace("/\&[a-z0-9]+=[0-9]+$/i","",$myString);
if you only want the &page=1-type parameters, the last line would be
$myNewString = preg_replace("/\&page=[0-9]+/i","",$myString);
if you also want to get rid of the possibility that page is the only or first parameter:
$myNewString = preg_replace("/[\&]*page=[0-9]+/i","",$myString);
Thank you guys but i think i have found the better solution, #KingCrunch had suggested a solution i extended and converted it into function. the below function can possibly remove or unset any URI variable without any regex hacks being used. i am posting it as it might help someone.
function unset_uri_var($variable, $uri) {
$parseUri = parse_url($uri);
$arrayUri = array();
parse_str($parseUri['query'], $arrayUri);
unset($arrayUri[$variable]);
$newUri = http_build_query($arrayUri);
$newUri = $parseUri['path'].'?'.$newUri;
return $newUri;
}
now consider the following uri
index.php?properties&status=av&page=1
//To remove properties variable
$url = unset_uri_var('properties', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?page=1&status=av
//To remove page variable
$url = unset_uri_var('page', basename($_SERVER['REQUEST_URI']));
//Outputs index.php?properties=&status=av
hope this helps someone. and thank you #KingKrunch for your solution :)
$pos = strrpos($_SERVER['REQUEST_URI'], '&');
$url = substr($_SERVER['REQUEST_URI'], 0, $pos - 1);
Documentation for strrpos.
Regex that works on every possible situation: /(&|(?<=\?))page=.*?(?=&|$)/. Here's example code:
$regex = '/(&|(?<=\?))page=.*?(?=&|$)/';
$urls = array(
'index.php?properties&status=av&page=1',
'index.php?properties&page=1&status=av',
'index.php?page=1',
);
foreach($urls as $url) {
echo preg_replace($regex, '', $url), "\n";
}
Output:
index.php?properties&status=av
index.php?properties&status=av
index.php?
Regex explanation:
(&|(?<=\?)) -- either match a & or a ?, but if it's a ?, don't put it in the match and just ignore it (you don't want urls like index.php&status=av)
page=.*? -- matches page=[...]
(?=&|$) -- look for a & or the end of the string ($), but don't include them for the replacement (this group helps the previous one find out exactly where to stop matching)
You could use a RegEx (as Chris suggests) but it's not the most efficient solution (lots of overhead using that engine... it's easy to do with some string parsing:
<?php
//$url="http://localhost/index.php?properties&status=av&page=1";
$base=basename($_SERVER['REQUEST_URI']);
echo "Basename yields: $base<br />";
//Find the last ampersand
$lastAmp=strrpos($base,"&");
//Filter, catch no ampersands found
$removeLast=($lastAmp===false?$base:substr($base,0,$lastAmp));
echo "Without Last Parameter: $removeLast<br />";
?>
The trick is, can you guarantee that $page will be stuck on the end? If it is - great, if it isn't... what you asked for may not always solve the problem.
Having a brain freeze...
Have a URL which may be in any of the formats :
http://url.com/stuff
url.com/somestuff
www.url.com/otherstuff
https://www.url.com/morestuff
You get the picture.
How do I remove the .com part to leave just the various 'stuff' parts ? For example, the above would end up :
stuff
somestuff
otherstuff
morestuff
You could achieve that using the following code:
$com_pos = strpos($url, '.com/');
$stuff_part = substr($url, $com_pos + 5);
Click here to see the working code.
This should do the trick for you!
<?php
$url = "http://url.com/stuff";
$querystring = preg_replace('#^(https|http)?(://)?(www.)?([a-zA-Z0-9-]+)\.[a-zA-Z]{2,6}/#', "", $url);
echo $querystring;
I submitted this answer because I'm not very fond of solutions using explode() to handle this. Maybe your query string contains more slashes so, you'd have to write exceptions for those cases.
You can use explode to make an array, then get the last element from the array.
$str = 'http://url.com/stuff';
$arr = explode('/', $str);
echo end($arr); // 'stuff'
$path = parse_url('http://url.com/stuff', PHP_URL_PATH);
If you leave the second parameter unspecified you can return an array including the domain etc.
Use explode function to divide the string.
<?php
$url = "http://url.com/stuff";
$stuff = explode("/", $url);
echo $stuff[sizeof($stuff) - 1];
?>
I used sizeof to access to last element.
preg_replace("/^(https?:\/\/)?[^\/]+/" ,"", $url);