Remove unnecessary slashes from path

后端 未结 6 520
温柔的废话
温柔的废话 2021-02-06 08:00
$path = \'/home/to//my///site\';

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

I am trying to get this

6条回答
  •  执念已碎
    2021-02-06 08:34

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

提交回复
热议问题