views:

45

answers:

2

I am mainly C++ programmer who returns to PHP seasonly. Every time I return I spend time to get used to echo/print correct JavaScript/HTML/CSS regarding the single quote and double quote ...etc. I need an advice in the form of a set of rules to follow for good escaping practice.

Edit This is a small example for my bad working code that I need to follow a rule to get more readable :

$ret = "<a href=\"$url\"><img src=\"images/delete.png\" width=\"20\" height=\"20\"></img></a>";

Thanks

+1  A: 

The PHP documentation for Strings goes over the different ways string literals can be specified:

  • single quoted
  • double quoted
  • heredoc syntax
  • nowdoc syntax (since PHP 5.3.0)

Is this good enough?

Justin Ethier
Thanks @JustinEthier, In a signle line text output should I better use double quotes inside single quoted string and escape the double quotes or vice versa. You know ... there are many possibilities considering JavaScript, PHP, and HTML. Can you get me?
mmonem
You can do it either way; but if your outermost quotes are double it will expand any variables in the string (even if these are inside single quotes in the string), if they are single it won't.
Colin Fine
@mmonem In some scenarios you also can encapsulate the variable name in braces to avoid confusing the interpreter.
Codex73
@Colins, thanks, you started touching my problem. I know this but all the time I have questions like 'Does JavaScript has the same behavior?'. I need some rules, or say, best practice or a link to good article.
mmonem
@mmonem Example: If you output needs to be : echo "Why do you come to my {$variablename}s".... or echo "My Name is : {$names[8]}[Military]"..
Codex73
+2  A: 

I'd rather use the single quote syntax for working with HTML. Reasons:

  1. it's faster ( noticable with larger strings with a bigger number of iterations )
  2. it's easier to know where the vars are
  3. html attributes need to be escaped using htmlspecialchars()
  4. you don't have to escape every doublequote

So that string would look like:

$ret = '<a href="'.htmlspecialchars($url).'"><img src="images/delete.png" width="20" height="20"></img></a>';
Kemo