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>';
Related
PHP Code:
$name = 'click here';
echo '$name';
Here I am Expecting 'Click here' but my Output is:
$name
The PHP Manual addresses this accurately:
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
To solve the issue, use either one of these solutions:
echo "$name";
echo ''.$name.'';
<?php echo $name; ?>
Either use double quotes around your entire echo statement and escape the quotes in your HTML, or use the concantination operator .
Using double quotes:
"$name";
Using the concantination operator
''.$name.'';
Using double quotes causes PHP to evaluate all variables (replace them with their contents) within the string. However to do this you also have to escape the inner double quotes by making them \" so that PHP doesn't confuse them with the end of the string.
Using the concantination operator you are actually creating 3 different strings, the open tag, the contents of the variable, and the closing tag and then gluing them together using the . to make one complete string which is sent to echo.
Manual reference on strings
http://php.net/manual/en/language.types.string.php
The basics are anything within " (double quotes) is evaluated, anything within ' (single quotes) is not.
So for your code there are a few options
Replace single quotes with double quotes and escape embedded double quotes with \
echo "$name";
You can also replace the embedded double quotes with single quotes (i don't think html minds, not sure about html5)
echo "<a href='http://example.net/some.php' class='menu'>$name</a>";
You could also do a printf, this replace %s = string, with your value $name
printf('%s", $name);
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.
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 am pretty new to php but I'm stuck on this problem... Say i wait to put a link to another site with a given parameter, how do I do it correclty?
This is what i have now:
<html>
<body>
<?php
$param = "test";
echo "Click Here;
?>
</body>
</html>
Well, for starters, you might not wanna overuse echo, because (as is the problem in your case) you can very easily make mistakes on quotation marks.
This would fix your problem:
echo "Click Here";
but you should really do this
<?php
$param = "test";
?>
Click Here
You can do it a number of ways, depending on the type of quotes you use:
echo "<a href='http://www.whatever.com/$param'>Click here</a>";
echo "<a href='http://www.whatever.com/{$param}'>Click here</a>";
echo 'Click here';
echo "Click here";
Double quotes allow for variables in the middle of the string, where as single quotes are string literals and, as such, interpret everything as a string of characters -- nothing more -- not even \n will be expanded to mean the new line character, it will just be the characters \ and n in sequence.
You need to be careful about your use of whichever type of quoting you decide. You can't use double quotes inside a double quoted string (as in your example) as you'll be ending the string early, which isn't what you want. You can escape the inner double quotes, however, by adding a backslash.
On a separate note, you might need to be careful about XSS attacks when printing unsafe variables (populated by the user) out to the browser.
There's a shorthand-type way to do this that I have been using recently.
This might need to be configured, but it should work in most mainline PHP installations.
If you're storing the link in a PHP variable, you can do it in the following manner based off the OP:
<html>
<body>
<?php
$link = "http://www.google.com";
?>
Click here to go to Google.
</body>
</html>
This will evaluate the variable as a string, in essence shorthand for echo $link;
I recommend using the short ' instead of ". If you do so, you wont longer have to escape the double quote (\").
In that case you would write
echo 'Click Here';
But look onto nicolaas' answer "what you really should do" to learn how to produce cleaner code.
You can embed a variable into a double quoted string like my first example, or you can use concantenation(the period) like in my second example:
echo "Click Here";
echo 'Click Here';
Notice that I escaped the double quotes inside my first example using a backslash.
HI Jasper,
you can do this:
<?
sprintf("Click Here", $param);
?>
Heredoc may be an option, see example 2 here: http://php.net/manual/en/language.types.string.php