Remove backslash \ from string using preg replace of php
Asked Answered
B

5

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

Burge answered 30/8, 2013 at 7:9 Comment(1)
J
22

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

echo preg_replace('/\\\\/', '', $var);
Jiffy answered 30/8, 2013 at 7:16 Comment(0)
G
23

why would you use preg_replace when str_replace is much easier.

$str = str_replace('\\', '', $str);
Grozny answered 30/8, 2013 at 7:12 Comment(0)
J
22

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

echo preg_replace('/\\\\/', '', $var);
Jiffy answered 30/8, 2013 at 7:16 Comment(0)
W
17

You can also use stripslashes() like,

<?php echo stripslashes($var); ?>
Watterson answered 22/12, 2014 at 6:19 Comment(0)
R
4

This worked for me!!

preg_replace("/\//", "", $input_lines);
Rockefeller answered 31/1, 2018 at 12:14 Comment(1)
This will capture slash but not backslash.Cyclostome
K
3
$str = preg_replace('/\\\\(.?)/', '$1', $str);
Keeney answered 13/6, 2017 at 18:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.