single and double quotes in php variable - php

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.

Related

single qoute syntax printing in php [duplicate]

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>");

PHP writing Class and id as single quotes instead of double quotes. Why?

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.

Quotes within PHP echo breaking HTML value

I have a HTML form value as a PHP function: value='".$item->get_title()."' (This is in an echo statement hence the single quotes.) The problem is that if the returned title contains any quotes it breaks the value function.
Example: value="Kim Dotcom lawyer blasts US government" s "pattern of delay &quote;'>
As you can see it breaks at government. There is supposed to be an apostrophe after that.
Does anyone know a fix for this?
The fix: value='".htmlspecialchars($item->get_title(), ENT_QUOTES)."'
Use htmlspecialchars to escape output not meant to be rendered as HTML:
value="'.htmlspecialchars($item->get_title(), ENT_QUOTES).'"
By default, htmlspecialchars only escapes double quotes, not single quotes. If you want to escape both (and so maintain your practice of putting HTML values in single quotes), add ENT_QUOTES as the second parameter to htmlspecialchars.
try with htmlspecialchars
htmlspecialchars($item->get_title());
try:
value='".str_replace('"', '', $item->get_title())."'

How to use single quotes within double quotes in PHP?

Creating a link in PHP:
echo "click here";
This throws an error: Parse error: parse error, expecting 'T_STRING' or 'T_VARIABLE' or 'T_NUM_STRING'. How can you do this?
Also, mixing single and double quotes, and escaping double quotes reduces readability and always generates errors. Is there a better way to create quotes with another syntax, like %Q() in Ruby?
Working PHP 5.2.8.
The problem is your array variable interpolation. The syntax is either
"$row[id]"
or
"{$row['id']}"
So:
"click here"
See http://php.net/manual/en/language.types.string.php#language.types.string.parsing.
If quotes get confusing, which they can, try heredoc syntax:
echo <<< END_HTML
click here
END_HTML;
...just make sure that the END_HTML; is on a line by itself, with no indentation and no trailing whitespace. Here, heredoc is overkill. But for larger HTML blocks with lots of variables it can be much easier than escaping quotes everywhere.
PHP heredoc
Cheers
sprintf is your friend for complex strings with variables:
http://php.net/manual/en/function.sprintf.php
echo sprintf('click here', $currentFile, $row['id']);
Here I assume that $currentFile is a string (you could further manipulate the string, perhaps with urlencode) and $row['id'] is an integer.
Enclose the variables in {} like this {$currentFile} and {$row['id']}.
for named arrays inside of double quotes, you should not use single quotes:
echo "click here";
I suggest you to echo HTML-Code in single quotes and their tags in double quotes for the reason of clarity. When someone else looks over your code a ton of escaped quotes makes it just look complicated.
e.g
echo '<a id="testlink" alt="blabla" href="test.php?somevar='.$xy.'">Test</a>';

learning about single and double quotes (.),("), and (')

Can you tell me what is the different using (')single quotes inside (")quotes and (")quotes inside (')single quotes? and at concat, what is the meaning of this '".$bla."' I still can not distinguish them.
In SQL, anything with single quotes is considered a text based data type.
SQL uses double quotes for escaping keywords and non-ASCII characters.
This:
'". $bla ."'
..is PHP syntax. $bla is a PHP variable, the period is a string concatenation character (which is why there's one on both sides). So in this example, the content of the $bla variable is being concatenated into a string, where it will be surrounded by single quotes.
The main difference is the anything in a double quote is evaluated and anything in a single quote is not. There has been some discussion that it is better to use single quotes than double quotes so that PHP does not need to evaluate every aspect of the line to determine if it is a variable or not:
$good = 'really good';
echo "this is not $good"; //bad
echo 'this is' . $good; //good
It just keeps thing running faster and keeps the code looking cleaner.

Categories