14

I want to remove the backslash alone using php preg replace.

For example: I have a string looks like

$var = "This is the for \testing and i want to add the # and remove \slash alone from the given string";

How to remove the \ alone from the corresponding string using php preg_replace

Josua Marcel C
  • 3,122
  • 6
  • 45
  • 87
Vignesh Pichamani
  • 7,950
  • 22
  • 77
  • 115

5 Answers5

22

why would you use preg_replace when str_replace is much easier.

$str = str_replace('\\', '', $str);
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
roninblade
  • 1,882
  • 15
  • 15
20

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

echo preg_replace('/\\\\/', '', $var);
Bora
  • 10,529
  • 5
  • 43
  • 73
17

You can also use stripslashes() like,

<?php echo stripslashes($var); ?>
nim
  • 509
  • 6
  • 16
3
$str = preg_replace('/\\\\(.?)/', '$1', $str);
B.Asselin
  • 978
  • 10
  • 19
3

This worked for me!!

preg_replace("/\//", "", $input_lines);