php regex replace double backslash with single

十年热恋 提交于 2019-12-10 16:27:48

问题


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?


回答1:


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.




回答2:


You dont need to use regex for this, use

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

See the str_replace docs



来源:https://stackoverflow.com/questions/21076648/php-regex-replace-double-backslash-with-single

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!