How do I use single quotes inside single quotes?

前端 未结 7 1945
梦谈多话
梦谈多话 2020-12-31 14:10

Can anyone explain how to make this code work?

echo \'
Welcome
\'
相关标签:
7条回答
  • 2020-12-31 14:14
    echo "<div id=\"panel1-under\">Welcome ".$_SESSION['username']."</div>";
    

    or

    echo '<div id="panel1-under">Welcome '.$_SESSION['username'].'</div>';
    

    Quick Explain :

    • You don't have to reopen the tags inside a echo String (" ... ")
    • What I have done here is to pass the string "Welcome " concatenated to $_SESSION['username'] and "" (what the . operator does)
    • PHP is even smart enough to detect variables inside a PHP string and evaluate them :

      $variablename = "Andrew";

      echo "Hello $variablename, welcome ";

    => Hello Andrew, welcome

    More infos : PHP.net - echo

    0 讨论(0)
  • 2020-12-31 14:19

    Generally speaking, to use the single quote inside a string that is using the single quote as delimiter, just escape the single quote inside the string

    echo 'That\'s all, folks';
    

    It's not clear what the purpose of your code is, though.

    echo '<div id="panel1-under">Welcome <?php echo "$_SESSION['username']"; ?></div>';
    

    As you are already using PHP code, <?php echo is not necessary. If you are only trying to output the content of a session variable, then you can use

    echo '<div id="panel1-under">Welcome ' . $_SESSION['username'] . '</div>';
    
    0 讨论(0)
  • 2020-12-31 14:27

    Use the following code

    $data = $session['user'];
    echo "a big string and $data   thats simple"
    
    0 讨论(0)
  • 2020-12-31 14:36

    You need to concatenate your strings & variables.

    echo '<div id="panel1-under">Welcome ' . $_SESSION['username'] . '</div>';
    
    0 讨论(0)
  • 2020-12-31 14:37

    You can use double or single quotes inside double quotes.

    #Result: Hello "World" 's
    $a = '"World"';   
    echo "Hello $a 's";
    
    #Result: Hello "World" 's    
    echo "Hello \"World\" 's";
    

    You can also use double or single quotes inside single quotes. (Not recommended when building SQL queries)

    #Result: Hello World's "s
    echo 'Hello World\'s "s';
    
    0 讨论(0)
  • 2020-12-31 14:37

    Inside single quotes, variable names aren't parsed like they are inside double-quotes. If you want to use single-quoted strings here, you'll need to use the string concatenation operator, .:

    echo '<div id="panel1-under">Welcome <?php echo "'.$_SESSION['username'].'"; ?></div>';
    

    By the way: the answer to the question in the title is that in order to use a literal single-quote inside a single-quoted string, you escape the single-quote using a backslash:

    echo 'Here is a single-quote: \'';
    
    0 讨论(0)
提交回复
热议问题