How do I add a string after the last slash in url?
current url: https://example.org/gallery/images/my-image.jpg
I need to add the "thumbs/" character to the last slash
The function or php code must change the address as follows
https://example.org/gallery/images/thumbs/my-image.jpg
please guide me
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)),
"$dir/thumbs",
$string);
Or string functions:
$string = str_replace($s=strrchr($string, '/'), "/thumbs$s", $string);
Concatenate the strings.
<?php
$addString = "thumbs/";
$newURL = "https://example.org/gallery/images/" . $addString . "my-image.jpg";
echo $newURL;
Related
I have a URL string like
http://mydomain.com/status/statusPages/state/stack:3/my_link_id:1#state-9
I want to remove my_link_id:1 from this string. I know I can use any string replace function like
$goodUrl = str_replace('my_link_id:1', '', $badUrl);
But the problem is, the integer part is dynamic. I mean in my_link_id:1 the 1 is dynamic. It is the ID of the link and it can be from 0 to any number. So I want to remove my_link_id:along with any dynamic number from the string.
What I think I should remove part of the string from last / to #. But how can I do that?
you can use regular expressions:
$goodUrl = preg_replace('/(my_link_id:[0-9]+)/ig', '', $badUrl);
You can use preg_replace() php function
http://in1.php.net/preg_replace
CODE:
<?php $string = "http://mydomain.com/status/statusPages/state/stack:3/my_link_id:1#state-9";
echo $result = preg_replace('/(my_link_id:[0-9]+)/si', '', $string);
?>
Output :
http://mydomain.com/status/statusPages/state/stack:3/#state-9
May following help you
$strUrl = "http://mydomain.com/status/statusPages/state/stack:3/my_link_id:1#state-9";
$finalUrl = preg_replace('/(my_link_id:[0-9]+)/i', '', $strUrl);
echo $finalUrl;
and If you want remove also last / and # you follow this code
$strUrl = "http://mydomain.com/status/statusPages/state/stack:3/my_link_id:1#state-9";
$finalUrl = preg_replace('/(\/my_link_id:[0-9]+#)/i', '', $strUrl);
echo $finalUrl;
Hi i want to know how can i get substring from string after last slash?
In short i want to get the file name from path.
for example i got string like this:
test-e2e4/test-e2e4/test-e2e4/6.png
and i want to get 6.png how can i do that ?
I got dir only and the file name can be all format, it can be also something else then file
Or test-e2e4/test-e2e4/test-e2e4/aaaaa and want to get aaaaa
Regex maybe? Or maybe you know some nice functions which will do it for me ?
In addition to other replies, there's actually a function in PHP to do this: basename. Example:
$string = 'test-e2e4/test-e2e4/test-e2e4/6.png';
$base = basename($string); // $base == '6.png';
$string = 'test-e2e4/test-e2e4/test-e2e4/aaaaa';
$base = basename($string); // $base == 'aaaaa'
$string = '6.png';
$base = basename($string); // $base == '6.png'
Full details here: http://php.net/basename
Do like this..
$yourstring = 'test-e2e4/test-e2e4/test-e2e4/6.png';
$val = array_pop(explode('/',$yourstring)); // 6.png
You can try explode and array_pop functions to work this out:
$str = 'test-e2e4/test-e2e4/test-e2e4/aaaaa.png';
$str = explode('/', $str);
$filename = array_pop($str);
echo $filename; //Output will be aaaaa.png
...Or you can use the following regex:
[^\/]*$
You don't need to use regex for this, you can use substr() to get a portion of the string, and strrpos() to specify which portion:
$full_path = "test-e2e4/test-e2e4/test-e2e4/6.png"
$file = substr( $full_path, strrpos( $full_path, "/" ) + 1 );
substr() returns a portion of the string, strrpos() tells it to start from the position of the last slash in the string, and the +1 excludes the slash from the return value.
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'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, '/\\' );
}
I need to strip a URL using PHP to add a class to a link if it matches.
The URL would look like this:
http://domain.com/tag/tagname/
How can I strip the URL so I'm only left with "tagname"?
So basically it takes out the final "/" and the start "http://domain.com/tag/"
For your URL
http://domain.com/tag/tagname/
The PHP function to get "tagname" is called basename():
echo basename('http://domain.com/tag/tagname/'); # tagname
combine some substring and some position finding after you take the last character off the string. use substr and pass in the index of the last '/' in your URL, assuming you remove the trailing '/' first.
As an alternative to the substring based answers, you could also use a regular expression, using preg_split to split the string:
<?php
$ptn = "/\//";
$str = "http://domain.com/tag/tagname/";
$result = preg_split($ptn, $str);
$tagname = $result[count($result)-2];
echo($tagname);
?>
(The reason for the -2 is because due to the ending /, the final element of the array will be a blank entry.)
And as an alternate to that, you could also use preg_match_all:
<?php
$ptn = "/[a-z]+/";
$str = "http://domain.com/tag/tagname/";
preg_match_all($ptn, $str, $matches);
$tagname = $matches[count($matches)-1];
echo($tagname);
?>
Many thanks to all, this code works for me:
$ptn = "/\//";
$str = "http://domain.com/tag/tagname/";
$result = preg_split($ptn, $str);
$tagname = $result[count($result)-2];
echo($tagname);