2017-07-20 20 views
-2

我想做一个简单的事情来改变斜线在文件路径中反斜线。 Windows 7操作系统str_replace的奇怪行为

<?php 
$fileName = "C:\migration\files\gallery\2c1c7e72-781e-4347-ab39-6e77409b93d5.json"; 
echo $fileName."<br>"; 
echo str_replace ("\\","/", $fileName); 
$fileContent = file_get_contents($fileName); 
echo $fileContent; 
exit(); 

我运行通过Apache命令行此代码,和我看到奇怪的结果

C:\migrationiles\galleryc1c7e72-781e-4347-ab39-6e77409b93d5.json 

第二斜线得到以字母F“\ F”和第四斜线消失与2号消失“/ 2” 你们可以解释我怎么可能?

+3

你也没能逃脱斜线在'$ fileName'变量 –

+5

嗯,这是怎么回事on - [如果字符串用双引号(“)括起来,PHP将解释以下特殊字符的转义序列:...](http://www.php.net/manual/en/language.types。 string.php#language.types.string.syntax.double) – CBroe

+2

使用单引号。https://eval.in/835384'str_replace'与它无关。 – chris85

回答

2

这只是因为逃生排序字符发生,你不能直接在php中打印\,要打印\你应该写它为\\。使用这样的从您的字符串替换双反斜线

$newstr = str_replace('\\\\', '/', $fileName); 

或简单地使用正则表达式,作为

$newstr = preg_replace('/\\\\/', '/', $fileName); 
+0

由于双引号引起的'$ fileName'赋值处被破坏。 – chris85

+1

我觉得CBroe [引用](https://stackoverflow.com/questions/45223196/weird-behavior-of-str-replace#comment77412638_45223196)的手册是*解释。 –

+0

@ Fred-ii-是的,这是正确的,我们得到更多的解释和例子 –