【问题标题】:Issues while using Quotes in PHP在 PHP 中使用引号时的问题
【发布时间】:2012-05-08 19:23:13
【问题描述】:

我了解到引号在 PHP 中并不重要。

但是在下面的代码中,如果我尝试在eval() 中使用单引号;我收到错误,另一方面代码可以正常使用双引号。

$a = '2';
$b = '3';
$c = '$a+$b';
echo $c.'<br/>';
eval("\$c = \"$c\";");
//eval('\$c = \'$c\';');  //Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING
echo $c;

【问题讨论】:

  • 谁告诉你报价不重要?
  • 单引号内的内容不会被解释。双引号内的东西是。引号很重要。

标签: php quotes


【解决方案1】:

PHP.net 表示转义序列在使用单引号时不会展开。

【讨论】:

    【解决方案2】:

    引号很重要 ;-)

    <?php
    
    $color = "red";
    
    echo "My car is $color"; // Outputs "My car is red"
    echo 'My car is $color'; // Outputs "My car is $color"
    
    ?>
    

    【讨论】:

      【解决方案3】:

      与双引号不同,PHP 不解析单引号中的变量。

      示例:

      $name = 'John';
      echo 'hello $name'; // hello $name
      echo "hello $name"; // hello John
      

      More Information


      仅供参考,出于安全原因,在生产环境中使用eval 不是一个好主意。

      【讨论】:

        【解决方案4】:

        使用evalbad idea 但如果你是为learning purpose 这样做,那么正确的方法是

          eval("\$c = \$c;");
        

        【讨论】:

        • 感谢您的回复。我有一个矿石怀疑。我可以知道为什么我们用backslash 转义$c。
        【解决方案5】:

        don't use eval 并在此处更新您的string-quoting skills

        【讨论】:

          【解决方案6】:

          以下示例摘自:The PHP Manual

          <?php
          echo 'this is a simple string';
          
          echo 'You can also have embedded newlines in 
          strings this way as it is
          okay to do';
          
          // Outputs: Arnold once said: "I'll be back"
          echo 'Arnold once said: "I\'ll be back"';
          
          // Outputs: You deleted C:\*.*?
          echo 'You deleted C:\\*.*?';
          
          // Outputs: You deleted C:\*.*?
          echo 'You deleted C:\*.*?';
          
          // Outputs: This will not expand: \n a newline
          echo 'This will not expand: \n a newline';
          
          // Outputs: Variables do not $expand $either
          echo 'Variables do not $expand $either';
          ?>
          

          【讨论】:

            猜你喜欢
            • 2011-04-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-07-22
            • 2012-10-28
            • 2023-03-08
            • 2013-12-25
            • 1970-01-01
            相关资源
            最近更新 更多