dstwfcz1377 2012-03-28 04:23
浏览 16
已采纳

PHP语法中的“\”实际意味着什么?

I have a piece of code and i keep getting syntax errors for codes like thess :

$query ="SELECT * from `jos_menu` where `id` = ".'\".$parent.'\";

Now when i reformat it as :

$query ="SELECT * from `jos_menu` where `id` = ".$parent;

That is when i remove : '\" it works fine. So i am just wondering, what does ('\") actually do ???

  • 写回答

6条回答 默认 最新

  • dtry54612 2012-03-28 05:03
    关注

    The only problem with

    $query ="SELECT * from `jos_menu` where `id` = ".'\".$parent.'\";
    

    Is that you missed a few ':

    $query ="SELECT * from `jos_menu` where `id` = ".'\"'.$parent.'\"';
    

    In PHP, a string can either be:

    $var = 'This is a string';

    Or

    $var = "This is a string";

    If you want to put " inside a string that you already started with ", you need tell PHP that you don't want your second " to end the string but use the character " as part of the string itself. This is what \" does. It tells PHP that Don't give the " character any special meaning; since normally if you started the string with ", the next " would end the string.

    \ means remove any "special" meaning to the next character

    This only works if the character after the \ would have had special meaning. Some examples:

    Suppose we want to print Hello "World". I am a string!:

    $var = "Hello "World". I am a string!";
    

    In this example we will have errors. Since we started the string with ", the next " will close the string. So what PHP thinks:

    1. " Start of string
    2. Hello part of string variable.
    3. " Hey, since I saw that the string was started with ", this must mean the end of it!
    4. World" <-- Error

    Stop processing and throw errors.

    However, if we write:

    $var = "Hello \"World\". I am a string!";
    

    Now, PHP thinks:

    1. " Start of string
    2. Hello part of string variable
    3. \ Ah, okay, the next character I should remove any special meaning
    4. " Okay, this is immediately after \, so I just use it normally, as a ".
    5. World part of string
    6. \ Okay, the next character I will remove any special meaning
    7. " This is now a normal "
    8. . I am a string! - part of string variable.
    9. " Ah! Since the string was started with ", this must be the ending.
    10. ; ends statement.

    Hopefully this clarifies things for you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥40 图书信息管理系统程序编写
  • ¥15 7-1 jmu-java-m02-使用二维数组存储多元线性方程组
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题