Search code examples
phpregexescapingpreg-replacebackslash

Replace single backslash with two backslashes using preg_replace()


I'm trying to replace \ with \\ but it fails, it can't escape the \\ character.

My function call:

preg_replace('\', '\\', 'text to \ be parsed');

How can I escape all backslashes?


Solution

  • Use 4 backslashes and please don't forget the delimiters:

    echo echo preg_replace('~\\\\~','\\\\\\\\','text to \\ be parsed');

    Online demo

    Explanation: When PHP parse \\\\ it will escape \\ two times, which means it becomes \\, now when PHP passes it to the regex engine, it will receive \\ which means \.