Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use single quotes inside single quotes?

Tags:

html

php

quotes

Can anyone explain how to make this code work?

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

I've tried removing the single quotes (echo '<div id="panel1-under">Welcome <?php echo "$_SESSION[username]"; ?></div>';), but it doesn't work.

like image 669
Joey Morani Avatar asked Aug 01 '10 21:08

Joey Morani


People also ask

How do you escape a single quote from a single quote?

No escaping is used with single quotes. Use a double backslash as the escape character for backslash.

How do you quote multiple quotes in one sentence?

When multiple quotation marks are used for quotations within quotations, keep the quotation marks together (put periods and commas inside both; put semi-colons, colons, etc., outside both).

What is the escape character for single quote?

Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.

Can you quote with single quotes?

Single quotation marks are used to indicate quotations inside of other quotations. “Jessie said, 'Goodbye,'” Ben said. This is Ben talking, so his words go in quotation marks. But because we're quoting Ben quoting someone else, Jessie, we use single quotation marks to indicate the quote within the quote.


2 Answers

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: \'';
like image 117
Hammerite Avatar answered Oct 02 '22 00:10

Hammerite


Generally speaking, to use the single quote inside a string that is using the single quote as delimiter, you 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 trying to output the content of a session variable, you can use the following code.

echo '<div id="panel1-under">Welcome ' . $_SESSION['username'] . '</div>';
like image 45
apaderno Avatar answered Oct 02 '22 00:10

apaderno