marvinas
marvinas

Reputation: 71

replace single slash with double slash, 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);

Upvotes: 5

Views: 17893

Answers (4)

chirag
chirag

Reputation: 1

It is possible using following code:

<?php  $str = addcslashes("Hello World!","W");?>  
<?php echo $str;?> <br/>    
<?php $str2 = addcslashes($str,"W");     
echo $str2;        
?>

Upvotes: -1

Poelinca Dorin
Poelinca Dorin

Reputation: 9703

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));

Upvotes: 7

Pekka
Pekka

Reputation: 449385

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.

Upvotes: 4

codaddict
codaddict

Reputation: 454950

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 ".

Upvotes: 6

Related Questions