PHP preg_replace \
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2222643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP preg_replace \
提问by Oliver Bayes-Shelton
Really simple question: how can I preg_replacethe backslash character?
非常简单的问题:我如何才能preg_replace使用反斜杠字符?
回答by Johnco
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).
是的,但你需要逃避它。当在正则表达式\\中使用它时,在替换中使用它时,使用\\\\(这将变成\\将被解释为单个反斜杠的)。
回答by Pekka
You need to escape the backslash: \\
您需要转义反斜杠: \\
From the manual on preg_replace:
To use backslash in replacement, it must be doubled (
"\\\\"PHP string).
要使用反斜杠替换,它必须加倍(
"\\\\"PHP 字符串)。
Alternatively, use preg_quoteto prepare a string for a preg_*operation.
或者,preg_quote用于为preg_*操作准备字符串。
回答by adesst
You could try
你可以试试
$a = "\\";
$a = preg_replace('/\\/','/',$a);
Output:
输出:
'//'
回答by Marek Karbarz
Escape \with \: \\
逃生\有\:\\
preg_replace('/\/', 'REMOVED BACKSLASH', 'sometest\othertest');
回答by Sarfraz
Use it twice eg \\
使用它两次,例如 \\
回答by Sakthikanth
This code works for me
这段代码对我有用
$text = "replace \ backslash";
$rep = "";
$replace_text = preg_replace( '/\\{1}/',$rep,$text);
echo $replace_text;
Output :
输出 :
replace backslash
替换反斜杠

