Remove Trailing Slash From String PHP - php

Is it possible to remove the trailing slash / from a string using PHP?

Sure it is, simply check if the last character is a slash and then nuke that one.
if(substr($string, -1) == '/') {
$string = substr($string, 0, -1);
}
Another (probably better) option would be using rtrim() - this one removes all trailing slashes:
$string = rtrim($string, '/');

This removes trailing slashes:
$str = rtrim($str, '/');

Long accepted, however in my related searches I stumbled here, and am adding for "completeness"; rtrim() is great, however implemented like this:
$string = rtrim($string, '/\\'); //strip both forward and back slashes
It ensures portability from *nix to Windows, as I assume this question pertains to dealing with paths.

rtrim
Use rtrim cause it respects the string doesnt end with a trailing slash

Yes, it is!
http://php.net/manual/en/function.rtrim.php

Related

How to update a path having an invalid slash?

I have a Path which is not valid:
C:\xampp\htdocs\laposte\app\webroot\img/Penguins.jpg
how to change the string having forward slashes only e.g
C:/xampp/htdocs/laposte/app/webroot/img/Penguins.jpg
my idea is to extract the words out of the string and then rebuild the string with forward slash.
how do you do that?
Use realpath function.
$str = realpath("C:\\xampp\\htdocs\\laposte\\app\\webroot\\img/Penguins.jpg");
echo $str; //C:\xampp\htdocs\laposte\app\webroot\img\Penguins.jpg
Or directly :
$str = str_replace('\\', '/', $str);
echo $str; //C:/xampp/htdocs/laposte/app/webroot/img/Penguins.jpg
I think that your path is OK for windows, except for the last slash. It should be backslash like this:
C:\xampp\htdocs\laposte\app\webroot\img\Penguins.jpg
It's better to use constant DIRECTORY_SEPARATOR rather than / to separate your path. It'll completely fix your problem.
Use string replace function in php:
echo str_replace("\\","/","C:\xampp\htdocs\laposte\app\webroot\img/Penguins.jpg");

Remove trailing slash on domain extensions without trailing directory

I'm importing data from a csv and I've been looking high and low for a particular regular expression to remove trailing slashes from domain names without a directory after it. See the following example:
example.com/ (remove trailing slash)
example.co.uk/ (remove trailing slash)
example.com/gb/ (do not remove trailing slash)
Can anyone help me out with this or at least point me in the right direction?
Edit: This is my progress so far, I've only matched the extension at the moment but it's picking up those domains with trailing directories.
[a-z0-9\-]+[a-z0-9]\/[a-z]
Many thanks
I don't know how it would compare to a regular expression performance-wise, but you can do it without one.
A simple example:
$string = rtrim ($string, '/');
$string .= (strpos($string, '/') === false) ? '' : '/';
In the second line I'm only adding a / at the end if the string already contains one (to separate domain from folder).
A more solid approach would probably be to only rtrim if the first / found, is the last character of the string.
not sure,
but you can try this,
if it is a $_SERVER['SERVER_NAME'] only then remove slash otherwise keep it
because $_SERVER['SERVER_NAME'] will return URL without any directory
try this
/^(http|https|ftp)\:\/\/[a-z0-9\-\.]+\.[a-z]{2,3}(:[a-z0-9]*)?\/?([a-z0-9\-\._\?\,\'\/\\\+&%\$#\=~])*$/i
you could test for a match on /[a-z]/, then remove the last charater if it's not found.
this is javascript, but it'd be similar in php.
/\/[a-z]+\//
var txt = 'example.com/gb/';
var match = txt.match(/\/[a-z]+\//);
if (!match) {
alert(txt.substring(txt,txt.length-1));
}
else {
alert(txt);
}
http://jsfiddle.net/xjKTS/
Try this, it works:
<?
$result = preg_replace('/^([^\/]+)(\/)$/','$1',$your_data);
?>
I have tested like this:
$reg = '/^([^\/]+)(\/)$/';
echo preg_replace($reg,'$1',$str1);//example.com
echo preg_replace($reg,'$1',$str2);//example.co.uk
echo preg_replace($reg,'$1',$str3);//example.com/gb/
?>

How to fix a path with regex in php for PATHS and not break URLs?

I want to replace // but not ://. I'm using this function to fix broken urls:
function fix ($path)
{
return preg_replace( "/\/+/", "/", $path );
}
For example:
Input:
a//a//s/b/d//df//a/s/
Output (collapsed blocks of more than one slash):
a/a/s/b/d/df/a/s/
That is OK, but if I pass a URL I break the http:// part, and end up with http:/. For example:
http://www.domain.com/a/a/s/b/d/df/a/s/
I get:
http:/www.domain.com/a/a/s/b/d/df/a/s/
I want to keep the http:// intact:
http://www.domain.com/a/a/s/b/d/df/a/s/
You can solve it rather easily using a negative lookbehind:
function fix ($path)
{
return preg_replace("#(?<!:)/{2,}#", "/", $path);
}
Note that I've also changed your delimiter from / to #, so you don't have to escape slashes.
Working example: http://ideone.com/6zGBg
This can still match the second slash if you have more than two (file://// -> file://). If this is a problem, you can use #(?<![:/])/{2,}#.
Example: http://ideone.com/T2mlR
return preg_replace("/[^:]\/+/", "/", $path);

removing dots and slashes regex - non relative

how could I remove the trailing slashes and dots from a non root-relative path.
For instance, ../../../somefile/here/ (independently on how deep it is) so I just get /somefile/here/
No regex needed, rather use ltrim() with /. . Like this:
echo "/".ltrim("../../../somefile/here/", "/.");
This outputs:
/somefile/here/
You could use the realpath() function PHP provides. This requires the file to exist, however.
If I understood you correctly:
$path = "/".str_replace("../","","../../../somefile/here/");
This should work:
<?php
echo "/".preg_replace('/\.\.\/+/',"","../../../somefile/here/")
?>
You can test it here.
You could try :
<?php
$str = '../../../somefile/here/';
$str = preg_replace('~(?:\.\./)+~', '/', $str);
echo $str,"\n";
?>
(\.*/)*(?<capturegroup>.*)
The first group matches some number of dots followed by a slash, an unlimited number of times; the second group is the one you're interested in. This will strip your leading slash, so prepend a slash.
Beware that this is doing absolutely no verification that your leading string of slashes and periods isn't something patently stupid. However, it won't strip leading dots off your path, like the obvious ([./])* pattern for the first group would; it finds the longest string of dots and slashes that ends with a slash, so it won't hurt your real path if it begins with a dot.
Be aware that the obvious "/." ltrim() strategy will strip leading dots from directory names, which is Bad if your first directory has one- entirely plausible, since leading dots are used for hidden directories.

Best way to remove trailing slashes in URLs with PHP

I have some URLs, like www.amazon.com/, www.digg.com or www.microsoft.com/ and I want to remove the trailing slash, if it exists, so not just the last character. Is there a trim or rtrim for this?
You put rtrim in your question, why not just look it up?
$url = rtrim($url,"/");
As a side note, look up any PHP function by doing the following:
http://php.net/functionname
http://php.net/rtrim
http://php.net/trim
(rtrim stands for 'Right trim')
Simple and works across both Windows and Unix:
$url = rtrim($url, '/\\')
I came here looking for a way to remove trailing slash and redirect the browser, I have come up with an answer that I would like to share for anyone coming after me:
//remove trailing slash from uri
if( ($_SERVER['REQUEST_URI'] != "/") and preg_match('{/$}',$_SERVER['REQUEST_URI']) ) {
header ('Location: '.preg_replace('{/$}', '', $_SERVER['REQUEST_URI']));
exit();
}
The ($_SERVER['REQUEST_URI'] != "/") will avoid host URI e.g www.amazon.com/ because web browsers always send a trailing slash after a domain name, and preg_match('{/$}',$_SERVER['REQUEST_URI']) will match all other URI with trailing slash as last character. Then preg_replace('{/$}', '', $_SERVER['REQUEST_URI']) will remove the slash and hand over to header() to redirect. The exit() function is important to stop any further code execution.
$urls="www.amazon.com/ www.digg.com/ www.microsoft.com/";
echo preg_replace("/\b\//","",$urls);

Categories