php regex用目录分隔符替换路径中的“any”斜杠

时间:2013-05-29 13:23:18

标签: php

我想尝试这样的路径:

一些/路径/这里 一些\其他\路径

并用PHP内置常量的DIRECTORY_SEPARATOR替换路径中的每个斜杠

我有这个:

$subject = '/asdf';
$var = preg_replace('#\\\\#', DS, $subject);
print $var;

但这不会取代,只会添加。

感谢您的帮助。

4 个答案:

答案 0 :(得分:4)

为什么不使用preg_replace

,而不是使用str_replace
$var = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $subject);

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

答案 1 :(得分:0)

因为您有2个斜杠,请尝试使用#\\#

答案 2 :(得分:0)

如果你没有明确需要正则表达式,那就是这样:

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

输出: some / path / here some / other / path

答案 3 :(得分:0)

它应该替换,而不是添加。但试试这个:

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

也应该有效。