3

I use netbeans, I try to replace \ with \\ but it fails , it can't escape the \\ character.

This is not a Netbeans issue , it's a PHP issue .

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

Any sollutions?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
KB9
  • 599
  • 2
  • 7
  • 16

3 Answers3

6

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

HamZa
  • 14,671
  • 11
  • 54
  • 75
2

Try the php chr() function and tell the preg_replace the char ascii code for \ and \\.

chr function

ascii code table

<?php
echo chr(52) . "<br>"; // Decimal value
echo chr(052) . "<br>"; // Octal value
echo chr(0x52) . "<br>"; // Hex value

preg_replace(chr(1),chr(2),'text'),

?>
Ionut Flavius Pogacian
  • 4,750
  • 14
  • 58
  • 100
1

This works: (using str_replace() rather than preg_replace())

$str = "text to \ be parsed";

$str = str_replace('\\', '\\\\', $str);

echo $str;
JohnnyFaldo
  • 4,121
  • 4
  • 19
  • 29