How to use double and single quotation marks?

9

Let's imagine the following example :

$color = "red";
echo ("<button onclick='change_background("/red"/);'>$color</button>");

What should I use when I have 3 levels using the example in change_background("/red"/); ?

I wanted to know how it works when they are inside each other type "primeiro nivel 'segundo nivel \'terceiro nivel\' '"

    
asked by anonymous 30.09.2015 / 14:07

3 answers

8

You need to read these two questions (and answers):

So it's good to know that you can, in most situations, set a standard to avoid confusion between PHP and JS code. Thus avoiding the escape character (the \ ).

This character is only needed when they get confused. For example. You are using double quotation marks in the PHP text. And inside it has double-quoted HTML code as well. These quotes there in HTML will close the PHP text and it is not what you want. Then use \" or \' , so the PHP interpreter will know that those quotes are part of the text and not the indicator that it is being closed.

It's annoying to do this. So it's better to choose one type for the code in one language and the other type in the other code.

I usually use single quotes in PHP and double in HTML. Except in rare cases this may prove to be worse.

When you have JS code inside HTML, you do not have much of a way, you have to go back to using the same type of quotation marks that HTML has already used or that PHP has already used and has to use the escape .

So it's best to leave JS code out of HTML as much as possible.

Note that in your sample code you are not using the escape backslash. In the description of the levels problem, you used it correctly.

PHP escape characters .

Escape Characters from JS .

    
30.09.2015 / 14:18
5

The problem is with your bars, which are reversed.

Test like this:

$color = "red"; 

echo ("<button onclick='change_background(\"red\");'>$color</button>");

Change the bars from "/" to "\".

    
30.09.2015 / 14:17
4

To solve this type of problem, I usually use the sprintf function, present in PHP . So I can type the block of text normally.

PHP

$button = '<button onclick="change_background(%s);">%s</button>';
$color = 'red';
echo sprintf($button, "'{$color}'", $color);

JS

if (!String.prototype.sprintf) {
  String.prototype.sprintf = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

var str = '<button onclick="change_background({0});">{1}</button>';
var color = 'red';
echo str.sprintf('"'+color+'"', color);

font

    
30.09.2015 / 14:59