简体   繁体   中英

Remove unnecessary slashes from path

$path = '/home/to//my///site';

I am trying to remove unnecessary forward slashes / from the path above

I am trying to get this results

/home/to/my/site

I've failed with str_replace , since i don't know the number of slashes.

Elegant solution

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 / .

Not-so Elegant solution

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

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

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!

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

只要改变长度,此代码用单斜杠替换双斜杠;

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM