【问题标题】:Escape character转义字符
【发布时间】:2011-01-15 07:31:33
【问题描述】:

我有这个功能:

<?php
function getmypost($number)
    {
        query_posts('p=1828');
        while (have_posts()) : the_post();
        the_title('<h1>', '</h1>');
        the_content();
        endwhile;
    }
?>

我需要将 1828 设为变量 我试过这个:

    query_posts('\'p='. $number .'\'');

但它不起作用。这样做的正确方法是什么?

【问题讨论】:

    标签: php string var


    【解决方案1】:

    如果我理解正确的话

    query_posts('p='.$number);
    

    应该可以。

    如果您需要在字符串中使用单引号 ',您可以转义 '

    query_posts('p=\''.$number.'\'');
    

    或使用双引号(更优雅,您可以将变量直接放入。Dominik 已经在他的回答中提出了这一点)

    query_posts("p='$number'");
    

    【讨论】:

    • 好的,它可以工作..我需要更多解释.. () 里面必须有与分隔符相同的 ''... 它怎么工作?
    • 你也可以使用 query_posts("p=$number");
    • ("p={$number}") 如果您有更复杂的变量名,例如 ("p={$numbers[$index]['foo']-&gt;value}")
    • 这是有效的,因为它本质上被更改为 p=valueofnumberhere。你以前有什么: query_posts('\'p='. $number .'\'');正在更改为 'p=valueofnumberhere' (请注意您的值如何在其中包含额外的引号)。如果您修改了您的内容 query_posts('p='. $number .'');它也可以,尽管最后的额外 .'' 是不必要的。
    • @marc-andre:您的示例中没有分隔符。您看到的 ' 是 PHP 中字符串的标记:de2.php.net/manual/en/language.types.string.php
    【解决方案2】:

    你可以使用

    query_posts("'p=$number'");
    

    【讨论】:

      猜你喜欢
      • 2011-02-21
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多