Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace single slash with double slash, php

Tags:

php

how replace single slash with double slash? I have this text:

"/data/folder/"

 and i need get

"//data//folder//"

i try with replace, but get error:

$data = str_replace("\", "\\", $data);
like image 914
marvinas Avatar asked Apr 12 '11 07:04

marvinas


3 Answers

You're talking about backslashes or normal slashes ? anyway check the code below for both of them :

$str = '\dada\dsadsa';
var_dump(str_replace('\\', '\\\\', $str));
$str = '/dada/dadda';
var_dump(str_replace('/', '//', $str));
like image 84
Poelinca Dorin Avatar answered Oct 17 '22 20:10

Poelinca Dorin


You want to replace forward slash but your str_replace is having back slash.

Try:

$data = str_replace("/", "//", $data);

Cause of error:

\ is used escaping. So the \ in "\" is actually escaping the second ".

like image 33
codaddict Avatar answered Oct 17 '22 21:10

codaddict


Regarding why you are getting an error, backslashes are escape characters in strings wrapped in double quotes ". You need to escape them as well:

str_replace("\\", "\\\\", $data);  

from what you are saying, you however probably want to use slashes, not backslashes, as shown by @codaddict.

like image 4
Pekka Avatar answered Oct 17 '22 21:10

Pekka