Alaa Gamal Alaa Gamal - 7 months ago 11
PHP Question

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.

Answer

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