php regex to replace 'any' slashes in a path with directory separator

前端 未结 4 2079
陌清茗
陌清茗 2021-01-14 12:40

I am trying to take paths like this:

some/path/here some\\other\\path

and replace each slash in the paths with PHP\'s DIRECTORY_SEPARATOR built in constant

相关标签:
4条回答
  • 2021-01-14 13:13

    Because you have 2 slashes try with #\\#

    0 讨论(0)
  • 2021-01-14 13:14

    It should replace, not add. But try this:

    preg_replace('/[\\]/', DS, $subject);
    

    Should also work.

    0 讨论(0)
  • 2021-01-14 13:22

    If you don't explicitly need regex, then this is the way:

    $string = "some/path/here some\other\path";
    $ds = DIRECTORY_SEPARATOR;
    $result = str_replace(array("/","\\"),$ds,$string);
    echo $result;
    

    Outputs: some/path/here some/other/path

    0 讨论(0)
  • 2021-01-14 13:30

    Rather than using preg_replace, why not just use str_replace?

    $var = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $subject);
    

    http://us3.php.net/manual/en/function.str-replace.php

    0 讨论(0)
提交回复
热议问题