$path = \'/home/to//my///site\';
I am trying to remove unnecessary forward slashes /
from the path above
I am trying to get this
With preg_replace
you can obtain this with a single line of code:
preg_replace('#/+#','/',$str);
The pattern /+
will match the forwardslash /
one or more times, and will replace it with a single /
.
There are of course other ways to achieve this, for example using a while
loop.
while( strpos($path, '//') !== false ) {
$path = str_replace('//','/',$path);
}
This will call str_replace
until all occurrences of //
are replaced. You can also write that loop in a single line of code if you want to sacrifice readability (not suggested).
while( strpos( ($path=str_replace('//','/',$path)), '//' ) !== false );
Hello may this will helpful
Write this code in your .Htaccess file and check it..
# Prevent double slashes in URLs, e.g. //Blog and /Home//About
RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]
Hope it will help you!
if someone wants to remove extra slashes from URL without removing first two slashes after http/https:
$url = preg_replace('/([^:])(\/{2,})/', '$1/', $url);
(thanks to ツ Liverbool how to remove multiple slashes in URI with 'PREG' or 'HTACCESS')
You could use the build-in function realpath() for stripping slashes of existing files. But you will always end up with a canonicalized absolute pathname.
<?php
// 2 slashes
echo realpath('/etc//passwd') . PHP_EOL; // prints /etc/password
// 3 slashes
echo realpath('/etc///passwd') . PHP_EOL; // prints /etc/password
// 2 ..
echo realpath('/etc/../etc/passwd') . PHP_EOL; // prints /etc/password
?>
Please note that this function returns an error if the file does not exist.
Some important remarks from the docs:
realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and returns the canonicalized absolute pathname.
And
On windows realpath() will change unix style paths to windows style.
while(strlen($path) != (strlen($path = str_replace('//','/', $path))));
This code replaces double slashes with single slash, as long as it changes length;
It replaces (consecutive) occurences of / and \ with whatever is in DIRECTORY_SEPARATOR, and processes /. and /.. fine. Paths returned by get_absolute_path() contain no (back)slash at position 0 (beginning of the string) or position -1 (ending)
function get_absolute_path($path) {
$path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
$parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
$absolutes = array();
foreach ($parts as $part) {
if ('.' == $part) continue;
if ('..' == $part) {
array_pop($absolutes);
} else {
$absolutes[] = $part;
}
}
return implode(DIRECTORY_SEPARATOR, $absolutes);
}
A test:
var_dump(get_absolute_path('this/is/../a/./test/.///is'));
Returns: string(14) "this/a/test/is"