Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 350
KB9 Avatar asked May 21 '26 17:05

KB9


1 Answers

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 \.

like image 122
HamZa Avatar answered May 24 '26 05:05

HamZa