与字符不同,用双反斜杠替换单个反斜杠不适用于数字。有没有办法在PHP中完成此操作?。
$attributes = "red\blue\green";
echo "<br>".str_replace("\\", "\\\\", $attributes);
//Output: red\\blue\\green
echo "<br>".preg_replace("/\\\\/", "\\\\\\\\", $attributes);
//Output: red\\blue\\green
// Unlike for characters, it doesn't work for numbers
$attributes = "25\30\35\40\45";
echo "<br>".str_replace("\\", "\\\\", $attributes);
//Output: 25 %
echo "<br>".preg_replace("/\\\\/", "\\\\\\\\", $attributes);
//Output: 25 %
答案 0 :(得分:1)
这是由双引号引起的-更改为单引号,如下所示:
$attributes = '25\30\35\40\45';
echo "<br>".str_replace('\\', '\\\\', $attributes);
工作正常,双引号内的\
将字符串解析为octal notation-单引号将解析字符串形式。
答案 1 :(得分:-1)
您可以使用 preg_replace
$attributes = "red\blue\green";
$newstring = preg_replace('/\\\\/','\\\\\\\\',$attributes);
echo $newstring;
并与 str_replace
一起使用$attributes = '25\30\35\40\45';
$newstring = str_replace('\\','\\\\',$mystring);
echo $newstring;