2017-07-20 18 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-是的,這是正確的,我們得到更多的解釋和例子 –