Remove last character in a path string if it is a slash - php

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, '/\\' );
}

Related

php: Insert string before last slash in url

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;

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;

Using rtrim in php for specific purpose

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, '/'), '/');

(Solved) need php script to remove the slash from the end of the url [duplicate]

The code below removes "www.", etc. from the beginning of websites that are entered into a database. It works great.
Is there a way I could use similar code to remove a forward-slash from the tail-end of a website that is entered into the same database?
$remove_array = array('http://www.', 'http://', 'https://', 'https://www.', 'www.');
$site = str_replace($remove_array, "", $_POST['site']);
You can pass a string of characters that you want trimmed off of a string to the trim family of functions. Also, you could use rtrim to trim just the end of the string:
$site = rtrim($site, "/");
$site = preg_replace('{/$}', '', $site);
This uses a relatively simple regular expression. The $ means only match slashes at the end of the string, so it won't remove the first slash in stackoverflow.com/questions/. The curly braces {} are just delimiters; PHP requires matching characters and the front and back of regular expressions, for some silly reason.
Simplest method:
$url = rtrim($url,'/');
John was the first and I think his solution should be preferred, because it's way more elegant, however here is another one:
$site = implode("/", array_filter(explode("/", $site)));
Update
Thx. I updated it and now even handles things like this
$site = "///test///test//"; /* to => test/test */
Which probably makes it even cooler than the accepted answer ;)
Is that what You want?
$url = 'http://www.example.com/';
if (substr($url, -1) == '/')
$url = substr($url, 0, -1);
You could have a slash before the question mark sign and you could have the "?" sign or "/" in the parameters (.com/?price=1), so you shouldn't delete this every time. You need to delete only the first slash "/" before the question mark "?" or delete the last slash "/" if you have no question marks "?" at all.
For example:
https://money.yandex.ru/to/410011131033942/?&question=where?&word=why?&back_url=https://money.yandex.ru/to/410011131033942/&price=1
would be
https://money.yandex.ru/to/410011131033942?&question=where?&word=why?&back_url=https://money.yandex.ru/to/410011131033942/&price=1
And
https://money.yandex.ru/to/410011131033942/
would be
https://money.yandex.ru/to/410011131033942
The PHP code for this would be:
if(stripos($url, '?')) {
$url = preg_replace('{/\?}', '?', $url);
} else {
$url = preg_replace('{/$}', '', $url);
}
The most elegant solution is to use rtrim().
$url = 'http://www.domain.com/';
$urlWithoutTrailingSlash = rtrim($url, '/');
EDIT
I forgot about rtrim();
You could also play around parse_url().
$new_string = preg_replace('|/$|', '', $string);
Perhaps a better solution would be to use .htaccess, but php can also do it with something like this:
<?php
header('location: '.preg_replace("/\/$/","",$_SERVER['REQUEST_URI']));
?>

PHP - strip URL to get tag name

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

Categories