7

I do not want to use stripslashes() because I only want to replace "\\" with "\".

I tried preg_replace("/\\\\/", "\\", '2\\sin(\\pi s)\\Gamma(s)\\zeta(s) = i\\oint_C \\frac{-x^{s-1}}{e^x -1} \\mathrm{d}x');

Which to my disapointment returns: 2\\sin(\\pi s)\\Gamma(s)\\zeta(s) = i\\oint_C \\frac{-x^{s-1}}{e^x -1} \\mathrm{d}x

Various online regex testers indicate that the above should work. Why is it not?

4
  • what's your actual code? Are you doing $a = preg_replace(...$a) or are you only calling preg_replace without actually saving its result? Commented Jan 12, 2014 at 15:46
  • First of all: Try preg_replace('/\\\\/', '\\', '2\\sin(...');(single quotes). Then read up on str_replace(), egexes are the wrong tool for the job. Commented Jan 12, 2014 at 15:46
  • Can you use str_replace ('//', '/', $variable); Commented Jan 12, 2014 at 15:48
  • A related question (replace single \ with double \): stackoverflow.com/questions/5631946/… Commented Jan 12, 2014 at 15:49

2 Answers 2

11

First, like many other people are stating, regular expressions might be too heavy of a tool for the job, the solution you are using should work however.

$newstr = preg_replace('/\\\\/', '\\', $mystr);

Will give you the expected result, note that preg_replace returns a new string and does not modify the existing one in-place which may be what you are getting hung up on.

You can also use the less expensive str_replace in this case:

$newstr = str_replace('\\\\', '\\', $mystr);

This approach costs much less CPU time and memory since it doesn't need to compile a regular expression for a simple task such as this.

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

Comments

9

You dont need to use regex for this, use

$newstr = str_replace("\\\\", "\\", $mystr);

See the str_replace docs

3 Comments

Your code will throw a parse error. It should be $newqsstr = str_replace("\\\\", "\\", $mystr);.
@SharanyaDutta Thanks, I must have miscopied the replace call. Edited that it. Sorry for the mistake!
@UliKöhler Simpler and better, right, because with regex "/\\\\/" you would match a single backslash, as the engine needs an escaped backslash to match a literal backslash, beause the backslash has a special meaning in regex. So it would be "/\\\\{2}/" to match a double backslash with a double-quoted str pattern.

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.