PHP - 转义美元符号

标签 php

如何修改字符串以确保美元符号前面有奇数个反斜杠?

<?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/

相关文章:

php - 在 Symfony2 运行时包含 Zepto 或 jQuery

php - macOS Big Sur 下包含奇怪版本号的用户代理字符串

PHP - 这是进行这些更改的有效方法吗?

php - 在 PHP 中使用 TCPDF 将 SVG 转换为 PDF

php - 合并两个数组并按日期排序这个新数组

php - 将pdf文件上传到服务器并获取其url

php 和 mysql 用户跟踪和报告

php - 将参数传递给新窗口php

javascript - 重定向时强制页面刷新

linux - 从 CLI 和浏览器运行 PHP 代码给出不同的结果