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>");
Related
This question already has answers here:
Single and double quotes together as HTML attribute value?
(2 answers)
Closed 3 years ago.
I have a string that contains HTML-Code. And within that string I am assigning a method WITH AN ARGUMENT to the onclick-attribute. This attribute needs to be a string though.
This is the code.
This is how it looks like in HTML.
This is how it should look like in HTML.
I tried to put double quotes before and after, escape them, escape them with multiple backslahes, and many other things, nothing works. All ideas are appreaciated. :-)
This looks like a job for stripslashes(). Note however, that you can not use the same double quote (") or single qoutes (') for both the attribute assignment AND the string definition for the parameter. Therefore you want your result to look something like: onclick="removeTag('naruto')".
If you have them as double quotes in your original string (i.e. $row['description']), you can replace those, all put together like this:
echo 'blabla <a href="#" onclick="removeTag(' . str_replace('"', '\'', stripslashes($row['description'])) . ')">';
A tiny bit simpler approach might be to just trim double quotes and add your own single qoutes:
echo 'blabla <a href="#" onclick="removeTag(\'' . trim(stripslashes($row['description']), '"') . '\')">';
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.
I've tried all the combination I know of but can't get it right!
echo <<<EOF
Popup!
EOF;
I want to pass the string that is contained in $comments to the popup, but I can't seem to get the right combination of escape characters and concatenation. Help pls!
TIA
Edit: This is the HTML that goes into the string I mentioned.
$comments.= "<b>" . $row['comName'] . "</b><br><i>" . $row['comment'] . "</i><br><br>";
You need to escape the string to valid Javascript/JSON first to preserve Javascript syntax, then escape the Javascript to preserve the syntax of the HTML it's embedded in:
$js = sprintf('javascript:popup(%s)', json_encode($comments));
printf('Popup!', htmlspecialchars($js));
Since this is quite a pain, you should really try to go for unobtrusive Javascript, which separates Javascript from HTML.
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between single quote and double quote string in php
Can you use " and ' interchangeably, 100%? Or is there a reason or use for each? What is the difference exactly?
Observe for yourself:
$name = 'John';
echo "Hello $name" . '<br>';
echo 'Hello $name';
Result:
Hello John // result from double quotes
Hello $name // result from single quotes
As can be seen variables inside double quotes are parsed while in single quotes they aren't.
So when you put variables inside double quotes, they can be parsed and their correct value is output whereas with single quotes, variables are not parsed and you get the same output of variable name itself as in Hello $name.
Since variables inside single quotes aren't parsed, using them is just a little good when it comes to performance.
If there is no question of variables inside quotes, you can use them inter-changeably though keeping above performance tip in mind.
For more information, you can look at the official documentation.
Just to add to the great answer of Sarfraz, there are certain situations where you would want to use one or the other.
Single quotes ('') are always parsed slightly (minutely) faster than double quotes so if you are an optimization freak, a good rule of thumb is to use single quotes instead of double quotes if you will not be parsing any variables.
However, if you have tons of variables and don't want to do something like:
echo 'My name is ' . $name . '!';
then you're better off with double quotes.
However when dealing with html output, you may consider the hassle of escaping your double quotes too tedious to deal with:
echo "<p id=\"myParagraph\">$name</p>";
So in this case the vote goes to single quotes.
Another thing is that when you build SQL queries with PHP, you may notice that you might prefer using double quotes to be able to parse variables and avoid escaping the single quotes:
"SELECT * FROM CoolGuys WHERE Name = '$name'";
In the end it's all a matter of preferrence. :)
Good luck!