Oliver Bayes-Shelton
Oliver Bayes-Shelton

Reputation: 6292

PHP preg_replace the backslash \

Really simple question: how can I preg_replace the backslash character?

Upvotes: 20

Views: 30801

Answers (7)

sidiboss224
sidiboss224

Reputation: 11

If you want to remove backslash from text and don't want to see it anymore. then use this php function. But if it is a double backslash it will only remove one. stripslashes ($string)

Upvotes: 0

Pekka
Pekka

Reputation: 449405

You need to escape the backslash: \\

From the manual on preg_replace:

To use backslash in replacement, it must be doubled ("\\\\" PHP string).

Alternatively, use preg_quote to prepare a string for a preg_* operation.

Upvotes: 8

Sakthikanth
Sakthikanth

Reputation: 139

This code works for me

  $text = "replace \ backslash";
  $rep = "";
  $replace_text = preg_replace( '/\\\\{1}/',$rep,$text);
  echo $replace_text;

Output :

replace backslash

Upvotes: 3

adesst
adesst

Reputation: 307

You could try

$a = "\\\\";
$a = preg_replace('/\\\\/','/',$a);

Output:

'//'

Upvotes: 5

Johnco
Johnco

Reputation: 4150

Yes, but you need to escape it. When using it in the regexp use \\ to use it in the replacement, use \\\\ (that will turn into \\ that will be interpreted as a single backslash).

Upvotes: 27

Sarfraz
Sarfraz

Reputation: 382696

Use it twice eg \\

Upvotes: 0

Marek Karbarz
Marek Karbarz

Reputation: 29294

Escape \ with \: \\

preg_replace('/\\/', 'REMOVED BACKSLASH', 'sometest\othertest');

Upvotes: 2

Related Questions