I used to know this, but I guess it slipped my mind.
What's the code you put in the beginning and the end of a variable in php to allow both kind of quotes?
The personal rules I follow (not a silver bullet):
If there is no single quotes in the string - use '
If there is single quote(s) in the string - use "
If there are different types of quotes in the string - use ' or HEREDOC
I think you are thinking of heredocs.
Example:
echo <<<EOT
Some text here '' ""'
This should print a capital 'A': \x41
EOT;
Related
This question already has answers here:
single quote inside double quote in php
(3 answers)
Closed 9 years ago.
The below outputs
href="javascript:showBed(" a114:1')'
when I want it on the form
href="javascript:showBed('A114:1')"
in order to get javascript to work. I had a look at this site but coudn't get it to work so I gave up. Perhaps you could give me a hint on how the corrent syntax would be?
echo("<a href='javascript:showBed('" . $row['Bed'] ."')' target='main' class='larmlink'>link</a>");
Thanks =)
Your output is not what it would output, but it is how it would be interpreted (HINT: don't look at a parsed DOM tree, look at the source).
echo("<a href='javascript:showBed('" . $row['Bed'] ."')' ...
==>
echo("<a href=\"javascript:showBed('" . $row['Bed'] ."')\" ...
You really should be using the more standard double quotes around HTML element properties. As such, it is probably best to use single quotes in PHP. I would suggest this:
echo('link');
To print the double-quote character, you can escape it by doing \"
echo("<a href=\"javascript:showBed('" . $row['bed'] ."')\" target='main' class='larmlink'>link</a>");
Live demo
When you want to output variable data to JavaScript, it is good to use json_encode() so that all special characters are escaped automatically. The htmlspecialchars() escapes any values for use in the HTML attribute value.
echo '<a href="',
htmlspecialchars('javascript:showBed(' . json_encode($row['Bed']) . ')'),
'" target="main" class="larmlink">link</a>';
Note that I use single quotes for PHP string literals so that PHP doesn't have to search through my string for a variable to replace. You don't have to do this, but I recommend it.
I like to use sprintf (or printf, but sprintf is easier to refactor) for long strings like this so it's easy to see the template:
echo sprintf("<a href='javascript:showBed(\"%s\")' target='main' class='larmlink'>link</a>", $row['Bed']);
I'd also consider using addslashes on the $row['Bed'] variable in case it has quotes in it.
Using the heredoc syntax often makes code with mixed quotes easier to understand:
echo <<<EOD
link
EOD;
As others mentioned, if the value of your $row['Bed'] might contain single or double quotes, you have to escape it with addslashes.
You can use the heredoc syntax to avoid to escape anything:
echo <<<LOD
link
LOD;
Notice that if your variables contains some quotes you must use the addslashes function or str_replace before.
Another good practive is to separate systematically all the html content from php code:
<a href="javascript:showBed('<?php
echo $row['Bed'];
?>')" target="main" class="larmlink">link</a>
try this one:
echo("<a href='javascript:showBed(\"" . $row['Bed'] ."\")' target='main' class='larmlink'>link</a>");
How can I combine this code with all single and double quotes as it should be.
I have tried several combinations and I can't make it work.
This one is my last try so please help.
What would be a good approach when working with long strings?
$html .='';
I would move your styles to an external stylesheet to make it shorter, and then just escape the quotes like "\"" for " in the string.
$html .="";
This was not tested because I don't have your code :)
Best solution is to use HEREDOC, which completely eliminates the need for ANY quote escaping at the PHP level:
$html .= <<<EOL
<a href="onclick('\$.ajax({ etc.....
EOL;
Note that you'll still be bound by the quoting needs of whatever language(s) you're embedding in the heredoc. But at least you won't have to worry about causing a PHP syntax error because of unbalanced/unescaped quotes.
I follow the rule of: php strings are encapsulated in single quote, so attributes of html are in double quotes.
Any quote in the attribute must be an escaped single quote \'
so:
$html .='';
You should probably just escape the double-quotes inside the other double-quotes (if that makes sense). :)
$html .='';
That (or something similar) should work.
Getting very confused with echoing an HTML anchor with a variable inside.
<?php
echo ' Next';
?>
I've tried so many variations of lost which ones I've tried. One of the attempts was with curly brackets { but still nothing. I know I'm getting my single and double quotes muddled up!
Could somebody please put me straight on this one. Also, what is the rules for apostrophes and quotes in PHP. If I want to echo something, what shall I start it with, an apostrophe or a quote.
<?php
echo ' Next';
?>
If you want to do some math of other trickery inside an echo, you will need to surround it in brackets.
Edit: #DaveRandom points out that the exception to the trickery clause is $var++ and ++$var.
If you use ' when printing string, everything inside is treated as a text.
If you use ", variables passed inside are converted to the their values.
However it's impossible to do a math operations inside ". You have to escape it and do it in 'PHP way'.
<?php
echo ' Next';
?>
Use double quotes "something" and surround the variables with curly brackets when they are inside the quotes.
echo " <a href='?p={$current_page+1}'>Next</a>";
You can also use string concatenation, which basically means joining a few strings together:
echo 'something' . 'something else' . $my_variable;
As for escaping, if anywhere inside some quotes you want to insert a quote of the same type (e.g. if you surround your script with double quotes and you want to insert a double quote), you need to escape these quotes by prepending them with a backslash - \.
For example you want to output Text and you have surrounded it in double quotes, you need to escape these double quotes in the HREF attribute by prepending them with a backslash \, so the result should be Text.
The following are valid ways of escaping and displaying characters:
echo "it\" so nice to be here";
echo 'it\'s so nice to be here';
echo "it's so nice to be here"; // Different quotes, no need to escape
echo 'it"s so nice to be here'; // Different quotes, no need to escape
The following will result in an error:
echo 'it's so nice the be here';
Because the PHP interpreter will assume the expression to be ended with the quote found in it's, resulting in the rest of the line being treated is invalid code.
For more information you can read the PHP documentation on the echo() function and this wonderful article on Quotes and Strings as well.
I assume you want to do this:
echo ' Next';
You can try This
$link = ' %s';
printf($link, $current_page - 1, "Prev");
printf($link, $current_page + 1, "Next");
I am getting a lot of errors lately on a Joomla project and have found things like (in class code)...
return "<span class='...
or
echo "<h3 id='...
instead of
return "<span class=\"...
echo "<h3 id=\"...
This includes many times a variable in quotes, but it still finds it's way to my browser with single quotes. Before going through and changing these, I wanted to see what others have to say. My project is at http://dev.thediabetesnetwork.com.
I have looked this up and find a lot of conflicting information, so figured I would revive the discussion for the newest PHP/browser configurations and see if I am overlooking other details.
It's a lot easier to read without all the double quotes inside the string being escaped with \.
If you need to output a variable inside a string expression, double quotes must be used. If you are outputting HTML inside double-quotes, you can either use ' or \" to enclose HTML attributes. The first is preferred because it results in cleaner PHP code.
If you don't want your HTML to use single quotes, then you can just escape all of your quotes, use heredoc syntax, or concatenate your variables into the string like:
echo '<div class="test">' . $var . '</div>';
Browser accept both, thus there is no deeper reason to choose one before the other. From the PHP point-of-view it is slightly more readable with single quotes, because you can wrap strings in double quotes and use variable substition. Compare yourself
"<a href='$url'>Foo</a>"
"Foo"
'Foo'
Another solution is to substitute the content manually, for example
sprintf('Foo', $url);
Or heredoc
echo <<<HTML
Foo
HTML;
I would choose the one, that fits best into the current context (regarding the readability).
Double quote and single quotes have different functionality in php.
You can put a variable or even array into a string with double quotes but not so with single quotes.
Both are acceptable in HTML specification. Indeed even no quotes is if there's not spaces. Most people prefer that I know to have double quotes for the php so you can use variables without breaking up your code and readability because no backslashes.
return "<span class='foo'>$foo</span>";
return "<span class=\"foo\">$foo</span>";
return '<span class="foo">'.$foo.'</span>';
return '<span class=\'foo\'>'.$foo.'</span>';
All work but the first one, to most, is the easiest to read and type.
You can read all about php strings, double quotes, single quotes, heredoc and nowdoc syntax in php's documentation here: http://php.net/manual/en/language.types.string.php
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
Is example Heredoc syntax which allows you to pick your starting and ending delimeters for long multiline strings. Nowdoc is the same as heredoc but like single quotes, you can't put variables into the string.
You don't need to use double quotes if the string doesn't need evaluating (e.g. if it contains variables, etc). In fact, because double quotes causes the string to be evaluated, they're less efficient than using single quotes and concatenating.
Furthermore, it's convention to use double quotes inside HTML tags, so this is how I'd do it:
return '<span class="test">' . $var . '</span>';
In my opinion, Joomla is very poorly coded, and what you've posted is just another example of this.
Another advantage to this method, as you can see above, is that code highlighters and IEDs make it easy to differentiate between "static" strings and variables.
I try to use single quotes as much as possible and I've noticed that I can't use \n in single quotes. I know I can just enter a newline literally by pressing return, but that screws up the indentation of my code.
Is there some ASCII character or something that I can type that will produce newline when I'm using single quotes?
No, because single-quotes even inhibit hex code replacement.
echo 'Hello, world!' . "\xA";
echo 'hollow world' . PHP_EOL;
Use the constant PHP_EOL then it is OS independent too.
If you are echoing to a browser, you can use <br/> with your statement:
echo 'Will print a newline<br/>';
echo 'But this wont!';
FYI it is possible to get newlines into strings without double quotes:
printf('Please%1$sgive%1$sme%1$snewlines%1$s', PHP_EOL);
Which may be useful If your irrational fear of double quotes knows no bounds. Though I fear this cure may be worse than the disease.
I wonder why no one added the alternative of using the function chr():
echo 'Hello World!' . chr(10);
or, more efficient if you're going to repeat it a million times:
define('C_NewLine', chr(10));
...
echo 'Hello World!' . C_NewLine;
This avoids the silly-looking notation of concatenating a single- and double-quoted string.
The only escape sequence you can use in single quotes is for the single quote itself.
$foo = 'That\'s great';
The only way you could insert a new line into a string created with single quotes is to insert a literal newline
$bar = 'That\'s
cheating';
There IS a difference on using single VS double quotes in PHP
e.g:
1. echo '$var\n';
2. echo "$var\n";
in 1, PHP will print literally: $var\n
in 2, PHP will have to search the location in memory for $var, and return the value in that location, also, it will have to parse the \n as a new line character and print that result
We're in the range of millionths of a second, but there IS a difference in performance. I would recommend you to use single quotes whenever possible, even knowing you won't be able to perceive this performance increase. But I'm a paranoid developer when it comes to performance.
You may want to consider using <<<
e.g.
<<<VARIABLE
this is some
random text
that I'm typing
here and I will end it with the
same word I started it with
VARIABLE
More info at: http://php.net/manual/en/language.types.string.php
Btw - Some Coding environments don't know how to handle the above syntax.
You can use this:
echo 'Hello World' . "\n";
This worked well for me:
print_r('Hello world'.PHP_EOL);
No, according to documentation, PHP recognize no special symbol in single quotes. And there is no single reason to use single quotes as much as possible
in case you have a variable :
$your_var = 'declare your var';
echo 'i want to show my var here'.$your_var.'<br>';