简体   繁体   English

php正则表达式用目录分隔符替换路径中的“任何”斜杠

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

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并用 PHP 的 DIRECTORY_SEPARATOR 内置常量替换路径中的每个斜杠

I have this:我有这个:

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

but this doesn't replace, it only add.但这并不能取代,它只会增加。

Thanks for any help.谢谢你的帮助。

Rather than using preg_replace , why not just use str_replace ?与其使用preg_replace ,为什么不直接使用str_replace呢?

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

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

因为你有 2 条斜线尝试#\\\\#

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输出:一些/路径/这里一些/其他/路径

It should replace, not add.它应该替换,而不是添加。 But try this:但是试试这个:

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

Should also work.也应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM