Alaa Gamal Alaa Gamal - 6 months ago 5x
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


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


Elegant solution

With preg_replace you can obtain this with a single line of code:


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