59

I have the following url:

$str = "http://www.domain.com/data/images\flags/en.gif";

I'm using str_replace to try and replace backslashes with forward slashes:

$str = str_replace('/\/', '/', $str);

It doesn't seem to work, this is the result:

http://www.domain.com/data/images\flags/en.gif

6 Answers 6

125

you have to place double-backslash

$str = str_replace('\\', '/', $str);
4
  • @Subdigger: Technically that wasn't correct, but you could have waited a little longer to let him fix the code...
    – Dor
    Commented Jul 24, 2011 at 11:54
  • 2
    @genesis your answer is the same as his. Commented Jul 24, 2011 at 11:54
  • see below You need to escape "\" as well.
    – Subdigger
    Commented Jul 24, 2011 at 11:55
  • I think the syntax for str_replace() changed so that $str should now be the first argument.
    – randy
    Commented May 1, 2019 at 4:17
29
$str = str_replace('\\', '/', $str);
1
  • 3
    This answer was BEFORE accepted answer;) Should be marked as the correct one since it is the same;) Commented Jul 24, 2019 at 22:39
12

No regex, so no need for //.

this should work:

$str = str_replace("\\", '/', $str);

You need to escape "\" as well.

3
  • @Subdigger: the posting software replaced my double slashes by one because I forgot to use a "code" block. It's pretty lame of you to downvote and then post the exact same solution.
    – Sylver
    Commented Jul 24, 2011 at 11:59
  • @Sylverdrag: actually Subdigger was first poster of an answer ;)
    – genesis
    Commented Jul 24, 2011 at 12:08
  • @Genesis: Darn. Didn't see any answer when I posted, but this thing just goes so fast...
    – Sylver
    Commented Jul 24, 2011 at 14:12
5

You need to escape backslash with a \

  $str = str_replace ("\\", "/", $str);
0
2

Single quoted php string variable works.

$str = 'http://www.domain.com/data/images\flags/en.gif';
$str = str_replace('\\', '/', $str);
-2

You want to replace the Backslash?

Try stripcslashes:

http://www.php.net/manual/en/function.stripcslashes.php

1
  • 1
    This removes slashes, not replaces them like the question was asking for. Also, could you link to English versions of the PHP manual, please. ;)
    – Shane
    Commented Jul 24, 2011 at 12:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.