20

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

0

7 Answers 7

27

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

Sign up to request clarification or add additional context in comments.

2 Comments

$htmlRes = preg_replace("~\\~", "", $htmlRes); Warning: preg_replace(): No ending delimiter '~' found
That should be $htmlRes = preg_replace("~\\\\~", "", $htmlRes);. When PHP parses the string, the escape sequences are processed, and it's interpreted as "~\\~", which is then parsed by the regexp engine, as a single back slash.
8

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.

7 Comments

@ajk are you using single quotes or double quotes?
$the_name = preg_replace('\\\\', 'u', $the_name);
@aj in that case, I think using only two backslashes should work. Single-quoted and double-quoted strings have different escaping rules
Just looking to replace the backslash with nothing ("Susan\'s" -> "Susan's")
Yeah, I tried that too and it didn't work. In both cases, it ends up returning an empty string.
|
5

You could try

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

Output:

'//'

Comments

3

This code works for me

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

Output :

replace backslash

Comments

2

Escape \ with \: \\

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

Comments

0

Use it twice eg \\

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.