How to get last part of a string? - php

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.

Related

SPLIT URL in PHP

I have below URL in my code and i want to split it and get the number from it
For example from the below URL need to fetch 123456
https://review-test.com/#/c/123456/
I have tried this and it is not working
$completeURL = https://review-test.com/#/c/123456/ ;
list($url, $number) = explode('#c', preg_replace('/^.*\/+/', '', $completeURL));
Use parse_url
It's specifically made for this sort of thing.
You can do this without using regex also -
$completeURL = 'https://review-test.com/#/c/123456/' ;
list($url, $number) = explode('#c', str_replace('/', '', $completeURL));
echo $number;
If you wan to get the /c/123456/ params you will need to execute the following:
$url = 'https://review-test.com/#/c/123456/';
$url_fragment = parse_url($url, PHP_URL_FRAGMENT);
$fragments = explode('/', $url_fragment);
$fragments = array_filter(array_map('trim', $fragments));
$fragments = array_values($fragments);
The PHP_URL_FRAGMENT will return a component of the url after #
After parse_url you will end up with a string like this: '/c/123456/'
The explode('/', $url_fragment); function will return an array with empty indexes where '/' was extracted
In order to remove empty indexes array_filter($fragments); the
array_map with trim option will remove excess spaces. It does not
apply in this case but in real case scenario you better trim.
Now if you var_dump the result you can see that the array needs to
be reindexed array_values($fragments)
You should try this: basename
basename — Returns trailing name component of path
<?php
echo basename("https://review-test.com/#/c/123456/");
?>
Demo : http://codepad.org/9Ah83qaP
Subsequently you can directly take from pure regex to fetch numbers from string,
preg_match('!\d+!', "https://review-test.com/#/c/123456/", $matches);
print_r($matches);
Working demo
Simply:
$tmp = explode( '/', $completeUrl).end();
It will explode the string by '/' and take the last element
If you have no other option than regex, for your example data you could use preg_match to split your url instead of preg_replace.
An approach could be to
Capture the first part as a group (.+\/)
Then capture your number as a group (\d+)
Followed by a forward slash at the end of the line \/$/
This will take the last number from the url followed by a forward slash.
Then you could use list and skip the first item of the $matches array because that will contain the text that matched the full pattern.
$completeURL = "https://review-test.com/#/c/123456/";
preg_match('/(.+\/)(\d+)\/$/', $completeURL, $matches);
list(, $url, $number) = $matches;

Function to shorten a specific string

I have this string:
$str="http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg";
Is there a built-in php function that can shorten it by removing the ._SL110_.jpg part, so that the result will be:
http://ecx.images-amazon.com/images/I/418lsVTc0aL
no, there's not any built in URL shortener php function, if you want to do something similar you can use the substring or create a function that generates a short link and stores the long and short value somewhere in database and display only the short one.
well, it depends if you need a regexp replace (if you don't know the complete value) or if you can do a simple str_replace like below:
$str = str_replace(".SL110.jpg", "", "http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg");
You can use preg_replace().
For example preg_replace("/\.[^\.]+\.jpg$/i", "", $str);
I would recommend using:
$tmp = explode("._", $str);
and then using $tmp[0] for your purpose, if you make sure the part you want to get rid of is always separated by "._" (dot-underscore) symbols.
You can try
$str = "http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg";
echo "<pre>";
A.
echo strrev(explode(".", strrev($str), 3)[2]) , PHP_EOL;
B.
echo pathinfo($str,PATHINFO_DIRNAME) . PATH_SEPARATOR . strstr(pathinfo($str,PATHINFO_FILENAME),".",true), PHP_EOL;
C.
echo preg_replace(sprintf("/.[^.]+\.%s$/i", pathinfo($str, PATHINFO_EXTENSION)), null, $str), PHP_EOL;
Output
http://ecx.images-amazon.com/images/I/418lsVTc0aL
See Demo
you could do this substr($data,0,strpos($data,"._")), if what you want is to strip everything after "._"
No, it is not (at least not directly). Such URL shorteners usually generate unique ID and remember your original URL and generated ID. When you enter such url, you start a script, which looks for given ID and then redirect to target URL.
If you want just cut of some portion of your string, then assuming that filename format is as you shown, just look for 1st dot and substr() to that place. Or
$tmp = explode('.', $filename);
$shortName = $tmp[0];
If suffix ._SL110_.jpg is always there, then simply str_replace('._SL110_.jpg', '', $filename) could work.
EDIT
Above was example for filename only. Whole code would be:
$url = "http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg";
$urlTmp = explode('/', $url);
$fileNameTmp = explode( '.', $urlTmp[ count($urlTmp)-1 ] );
$urlTmp[ count($urlTmp)-1 ] = $fileNameTmp[0];
$newUrl = implode('/', $urlTmp );
printf("Old: %s\nNew: %s\n", $url, $newUrl);
gives:
Old: http://ecx.images-amazon.com/images/I/418lsVTc0aL._SL110_.jpg
New: http://ecx.images-amazon.com/images/I/418lsVTc0aL

isolate the number exists at the end of the URI php

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);

Match unique string in PHP between common characters

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

Preg_replace domain problem

I'm Stuck try to get domain using preg_replace,
i have some list url
download.adwarebot.com/setup.exe
athena.vistapages.com/suspended.page/
prosearchs.com/se/tds/in.cgi?4&group=5&parameter=mail
freeserials.spb.ru/key/68703.htm
what i want is
adwarebot.com
vistapages.com
prosearchs.com
spb.ru
any body can help me with preg_replace ?
i'm using this http://gskinner.com/RegExr/ for testing :)
using preg_replace, if the number of TLDs is limited:
$urls = array( 'download.adwarebot.com/setup.exe',
'athena.vistapages.com/suspended.page/',
'prosearchs.com/se/tds/in.cgi?4&group=5&parameter=mail',
'freeserials.spb.ru/key/68703.htm' );
$domains = preg_replace('|([^.]*\.(?:com|ru))/', '$1', $urls);
matches everything that comes before .com or .ru which is not a period. (to not match subdomains)
You could however use PHPs builtin parse_url function to get the host (including subdomain) – use another regex, substr or array manipulation to get rid of it:
$host = parse_url('http://download.adwarebot.com/setup.exe', PHP_URL_HOST);
if(count($parts = explode('.', $host)) > 2)
$host = implode('.', array_slice($parts, -2));
Following code assumes that every entry is exactly at the beginning of the string:
preg_match_all('#^([\w]*\.)?([\w]*\.[\w]*)/#', $list, $m);
// var_dump($m[2]);
P.S. But the correct answer is still parse_url.
Why use a regular expression? Of course it is possible, but using this:
foreach($url in $url_list){
$url_parts = explode('/', $url);
$domains[] = preg_replace('~(^[^\.]+\.)~i','',$url_parts[0]);
}
$domains = array_unique($domains);
will do just fine;
maybe a more generic solution:
tested by grep, I don't have php environment, sorry:
kent$ echo "download.adwarebot.com/setup.exe
dquote> athena.vistapages.com/suspended.page/
dquote> prosearchs.com/se/tds/in.cgi?4&group=5&parameter=mail
dquote> freeserials.spb.ru/key/68703.htm"|grep -Po '(?<!/)([^\./]+\.[^\./]+)(?=/.+)'
output:
adwarebot.com
vistapages.com
prosearchs.com
spb.ru

Categories