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