如何修改字符串以确保美元符号前面有奇数个反斜杠?
<?php
$string = file_get_contents('somefile.txt');
echo($string."\n");
$string=str_replace ('$' , '\$' ,$string);
echo($string."\n");
?>
一些文件.txt
$first
\$second
\\$third
\\\$forth
\\\\$fifth
输出
$first
\$second
\\$third
\\\$forth
\\\\$fifth
\$first
\\$second
\\\$third
\\\\$forth
\\\\\$fifth
最佳答案
你是单引号。在单引号中,美元符号不会被解析为任何东西。 php 中的单引号中没有自动解析任何内容。如果您使用双引号,它们会被自动解析:
echo "$var"; // this will print the value of $var;
echo '$var'; // this will print $var;
echo "\$var";// this escapes the dollar sign so it will print $var;
如果字符串是用双引号创建的,则不能在之后直接转义美元符号,因为它已经被解析为变量。
例子:
$var = 'hello';
$str = "$var";
此时,当 $str 的值是 hello 而不是 $var 时,您将尝试添加转义符\$。
关于PHP - 转义美元符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31640682/