-1

I've got a short and simple PHP script, in which I want to look for every series of two or more backslashes inside a string, and replace it with a single backslash:

<?php
    $link = 'www\\root\\\\test\\';
    echo preg_replace('/[\\]{2,}/', '\\', $link);
?>

So I guess that I actually escaped all the backslashes properly, but when I run the code, it gives me back an error that says that the terminating ] bracket could not be found. So it seems to me that this one is escaped instead of the backslash, which confuses me. Does escaping a backslash inside a character class actually take different methods than that?

StrikeAgainst
  • 556
  • 6
  • 23

1 Answers1

0

Ah alright, so I came across an answer myself:

preg_replace('/[\\\\]{2,}/', '\\', $link);

I need to double escape it, since PHP needs to escape it by itself first.

StrikeAgainst
  • 556
  • 6
  • 23