phpescaping

str_replace() fails to replace backslash followed by forward slash


I want to remove a special character from a string; for that I use the str_replace() function. However, it doesn't work for my script.

$path = "catalog\/demo\/samsung_tab_1.jpg";
$newPath = str_replace("\/", "/", $path);

But no replacements are made.

I want to get the output like:

catalog/demo/samsung_tab_1.jpg

Solution

  • Instead of \/ you can remove forward slash by using double backslashes:

    <?php
    $path= "catalog\/demo\/samsung_tab_1.jpg";
    $newPath = str_replace("\\","",$path); // replace with empty string ""
    echo $newPath; // catalog/demo/samsung_tab_1.jpg
    ?>