1

I want to replace my last \ with / on this URL string

C:\wamp\www\chm-lib\sekhelp_out\HTML\AS_BUILD.htm

I have tried this link, but no changes, I am missing something, please correct me where I am wrong.

Community
  • 1
  • 1
Rajesh Dey
  • 153
  • 2
  • 13

4 Answers4

2

Here is a solution using PHP's string functions instead of regex.

Do this:

$url = 'C:\wamp\www\chm-lib\sekhelp_out\HTML\AS_BUILD.htm';
$pos = strrpos($url, '\\');
$url = substr_replace($url, '/', $pos, 1);

echo $url;

To get this:

C:\wamp\www\chm-lib\sekhelp_out\HTML/AS_BUILD.htm

Explanation:

  1. Get the position of the last \ in the input string using strrpos()
  2. Replace that with / using substr_replace()

Note

It is important to pass '\\' instead of '\' to strrpos() as the first \ escapes the second.

Also note that you can shorten the code above to a single line if you prefer, but I thought it would be easier to understand as is. Anyway, here is the code as a one-liner function:

function reverseLastBackslash($url) {
    return substr_replace($url, '/', strrpos($url, '\\'), 1);
}
domsson
  • 4,553
  • 2
  • 22
  • 40
  • Ha, I just realized that the code was even more complicated than it had to be. I simplified it now, you might want to check the edit. (The previous version worked just fine, but was using `substr()` when it didn't need to) – domsson Apr 18 '17 at 12:33
2

You can try exploding the string as an array and imploding after popping off the last part, and connecting it back with a forward slash.

$array = explode('\','C:\wamp\www\chm-lib\sekhelp_out\HTML\AS_BUILD.htm');
$last = array_pop($array);
$corrected = implode('\',$array) . '/' . $last;
Lin De
  • 54
  • 3
  • Nice idea to use `explode()` / `implode()` here. Makes for a pretty clean solution. +1 – domsson Apr 18 '17 at 12:22
  • Oh, by the way, *"The answer above"* now refers to a different answer as at the point of your writing, so you might want to change that reference. – domsson Apr 19 '17 at 20:41
0

The backslash escaping is tricky:

preg_replace('/\\\\([^\\\\]*)$/', '/$1', "C:\\wamp\\www\\chm-lib\\sekhelp_out\\HTML\\AS_BUILD.htm")

You have to escape once for the literal string and once for the regular expression so a single \ needs to be \\\\ (1 x 2 x 2)

Mike
  • 2,429
  • 1
  • 27
  • 30
-1

Simply use this

 str_replace('\\','/','C:\wamp\www\chm-lib\sekhelp_out\HTML\AS_BUILD.htm');
D. Pachauri
  • 244
  • 2
  • 8