I am not much used to using rtrim and Reg expressions. So I wanted to get my doubt cleared about this:
Here is a url: http://imgur.com/r/pics/paoWS
I am trying to use rtrim function on this url to pick out only the 'paoWs' from the whole url.
Here is what i tried:
$yurl = 'http://imgur.com/r/pics/paoWS';
$video_id = parse_url($yurl, PHP_URL_PATH);
$yid=rtrim( $video_id, '/' );
And i am using '$yid' to hotlink the image from imgur. But What I get after trying this function is:
$yid= '/r/pics/paoWS'
How do I solve this?
rtrim is used for trimming down a string of certain characters or whitespace on the right-hand side. It certainly shouldn't be used for your purpose.
Assuming the URL structure will always be the same, you could just do something like this:
$yurl = 'http://imgur.com/r/pics/paoWS';
$video_id = parse_url($yurl, PHP_URL_PATH);
$parts = explode('/', $video_id)
$yid = end($parts);
You sould not use regular expressions (whitch are 'expensive') for a so 'simple' problem.
If you want to catch the last part of the URL, after the last slash, you can do :
$urlParts = explode('/', 'http://imgur.com/r/pics/paoWS');
$lastPart = end($urlParts);
rtim( strrchr('http://imgur.com/r/pics/paoWS' , '/') ); rtrim + strrchr
substr(strrchr('http://imgur.com/r/pics/paoWS', "/"), 1); substr + strrchr
rtrim() returns the filtered value, not the stripped characters. And your usage of it isn't proper too - it strips the passed characters from the right side. And you don't need parse_url() either.
Proper answers have been given already, but here's a faster alternative:
$yid = substr($yurl, strrpos($yurl, '/')+1);
Edit: And another one:
$yid = ltrim(strrchr($yurl, '/'), '/');
Related
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;
Well sorry for the probably misleading title. Wasn't sure how to describe it better.
When accessing the status page I want to get the attached ID. But I don't want to use GET fields (wordpress makes /status?id=2134 to /status/?id=1234 - that's the only reason actually).
So this is my url
http://foo.bar.com/status/1234/
I want to get 1234
Okay fine. I could use something like $_SERVER["REQUEST_URI"] + trim() for example. Probably regex would be the key to get this job done since one could do something like /status/1234/foo/bar/baz/.. But I'm wondering if there is something builtin with PHP to get this part of the url.
Use the parse_url() function, and extract it:
$url = 'http://foo.bar.com/status/1234/';
$path = trim(parse_url($url, PHP_URL_PATH), '/');
$items = explode('/', $path);
$num = array_pop($items);
var_dump($num);
You can also use a regular expression, if that tickles your fancy:
$url = 'http://foo.bar.com/status/1234/';
$path = parse_url($url, PHP_URL_PATH);
preg_match('~/status/(?P<num>\d+)/?~', $path, $result);
$num = isset($result['num']) ? $result['num'] : null;
var_dump($num);
Try to parses a URL and returns an associative array containing any of the various components of the URL that are present using parse_url, explode it using explode and finally select status id using end
Try like this
$url = 'http://foo.bar.com/status/1234/';
$statusId = explode('/',trim(parse_url($url, PHP_URL_PATH), '/'));
print end($statusId);
Demo Ex http://ideone.com/34iDnh
trim- http://php.net/trim
explode-http://php.net/explode
parse_url-[1]: http://php.net/manual/en/function.parse-url.php
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
I have url in the following types
http://domain.com/1/index.php
http://domain.com/2/index.php
http://domain.com/3/index.php
http://domain.com/4/index.php
I need to retrieve only the number from the url .
for example,
when i visit http://domain.com/1/index.php , It must return 1.
Have a look at parse_url.
$url = parse_url('http://domain.com/1/index.php');
EDIT: Take a look at $_SERVER['REQUEST_URI'], to get the current URL. Use that instead of $url['path'].
Then you can split $url['path'] on /, and get the 1st element.
// use trim to remove the starting slash in 'path'
$path = explode('/', trim($url['path'], '/'));
$id = $path[0]; // 1
Given the information provided, this will do what you ask... it's not what I would call a robust solution:
$url = $_SERVER['PATH_INFO']; // e.g.: "http://domain.com/1/index.php";
$pieces = explode("/", $url);
$num = $pieces[3];
split the server path by forward slashes (explode('/', $_SERVER['REQUEST_PATH']);)
remove empty entry from the beginning
take the first element
make sure it is an integer (intval(), or a simple (int) cast).
No need to use regular expressions for this.
You use preg_match() to match the domain and get the 1st segment.
$domain = http://www.domain.com/1/test.html
preg_match("/http:\/\/.*\/(.*)\/.*/", "http://www.domain.com/1/test.html");
echo $matches[1]; // returns the number 1 in this example.
I'm doing some url rewriting in PHP and need to find URLS with a slash at the end and then do a 301 redirect. I thought there'd be a simple PHP function to find last string, but I couldn't find anything. First instincts make m think I need to use regex, but I'm not 100%.
Here's one example:
http://domainx.com/characters/ I want to find a trailing slash and turn it into http://domainx.com/characters
So what function will help me check if the last character is a "/"?
A nice solution to remove safely the last / is to use
$string = rtrim($string, '/');
rtrim() removes all /s on the right side of the string when there is one or more.
You can also safely add exactly one single / at the end of an URL:
$string = rtrim($string, '/').'/';
You can use substr:
substr($str, -1)
This returns the last byte/character in a single-byte string. See also the multi-byte string variant mb_substr.
But if you just want to remove any trailing slashes, rtrim is probably the best solution.
And since you’re working with URLs, you might also take a look at parse_url to parse URLs as a trailing slash does not need to be part of the URL path.
$string[strlen($string)-1] gives you the last character.
But if you want to strip trailing slashes, you can do $string = rtrim($string, '/');. If there is no trailing slash, $string will remain unchanged.
You can use basename()
This will return characters for http://domainx.com/characters/ as well as http://domainx.com/characters
You can do like this:-
$page = $_SERVER['REQUEST_URI'];
$module = basename($page);
Then you can use the $module directly in your conditional logic without doing any redirects.
If you want to collect the last / trimmed URL then you can do this:-
If you are storing the project base url in a config file:-
BASE_URL = 'http://example.com'
then you can do this:-
$page = $_SERVER['REQUEST_URI'];
$module = basename($page);
$trimmedUrl = BASE_URL.'/'.$module;
You could preg_replace() a / at the end of the subject
$url = 'http://domainx.com/characters/';
$url = preg_replace('/(?:\/)$/', '', $url);
If you have php > 7.1
$string[-1]
Will give you the last character
http://sandbox.onlinephpfunctions.com/code/ff439889f14906749e4eb6328796c354c60f269b
Difference between rtrim and custom function:
<?php
$string0 = 'hi//';
$string1 = 'hello/';
$string2 = 'world';
function untrailingslashit( $string ) {
return $string[-1] === '/' ? substr( $string, 0, -1) : $string;
}
echo untrailingslashit($string0);
echo "\n";
echo untrailingslashit($string1);
echo "\n";
echo untrailingslashit($string2);
echo "\n";
echo rtrim($string0, "/");
Result:
hi/
hello
world
hi
With PHP 8
str_ends_with($string, '/');
New str_starts_with() and str_ends_with() functions are added into the core.
This is coming straight from WordPress:
function untrailingslashit( $string ) {
return rtrim( $string, '/\\' );
}