'Double quotes within php script echo
I have a line of php code that looks like this:
echo "<script>$('#edit_errors').html('<h3><em>Please Correct Errors Before Proceeding</em></h3>')</script>";
I would like to know how to add a font color to the text correctly. If I do this:
echo "<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>";
The word "red" is in black text and the compiler throws an error.
If I use single quotes around red, then the text does not show up at all.
Any help would be great. Thanks
Solution 1:[1]
use a HEREDOC, which eliminates any need to swap quote types and/or escape them:
echo <<<EOL
<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>
EOL;
Solution 2:[2]
Just escape your quotes:
echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";
Solution 3:[3]
You need to escape the quotes in the string by adding a backslash \ before ".
Like:
"<font color=\"red\">"
Solution 4:[4]
if you need to access your variables for an echo statement within your quotes put your variable inside curly brackets
echo "i need to open my lock with its: {$array['key']}";
Solution 5:[5]
You can just forgo the quotes for alphanumeric attributes:
echo "<font color=red> XHTML is not a thing anymore. </font>";
echo "<div class=editorial-note> There, I said it. </div>";
Is perfectly valid in HTML, and though still shunned, absolutely en vogue since HTML5.
CAVEATS
- It's only valid for mostly alphanumeric and dash combinations.
- Never ever do this with user input appended to attributes (those need quoting and
htmlspecialcharsor some whitelisting). - See also: When the attribute value can remain unquoted in HTML5
- In other news:
<font>specifically is somewhat outdated however.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marc B |
| Solution 2 | John Conde |
| Solution 3 | Ryan |
| Solution 4 | mark |
| Solution 5 | mario |
