Skip to content Skip to sidebar Skip to footer

Quoting Quotation Marks

Anyone got a way of thinking about this? I'm going a bit bats working on this: $toReturn .= ' function addProd(pExists) { document.getElementById('products').innerHTML

Solution 1:

Use a double escaped double quotes:

\\\"

In this way when this will get printed, it will become a simple escaped double quote (\") and it won't be in the innerHTML.

Solution 2:

Consider using the HEREDOC syntax. http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

<?php$my_string = <<<EOD
    <script type="text/javascript">
        var x = "this string has a ' known as a single quote!";
    </script>
EOD;


?>

The advantage with this syntax is being able to freely write your html or javascript without escaping quotes.

Update

Here is a little more info on HEREDOC.

First and foremost the most common error related to heredoc syntax is caused by whitespace. HEREDOC syntax requires an opening and closing identifier. In the example above I have used EOD as the identifier. It is important that the opening identifier has no whitespace after it and the closing identifier is on a new line, has no whitespace before it and no whitespace between the identifier and the semi-colon.

You do not have to use EOD as your identifier. You can use something more descriptive. I like to use an identifier that describes the block of code.

<?php$html = <<<HTML
    <html>
        <head>
            <title>Example html</title>
        </head>
        <body>
            <p class="paragraph">This is my html!</p>
        </body>
    </html>
HTML;

$javascript = <<<JAVASCRIPT
    <script type="text/javascript">
        var helloText = "Hello, my name is Jrod";
        alert(helloText);
    </script>
JAVASCRIPT;

?>

To use variables inside your heredoc syntax you will need to use curly braces around your variable in the code.

$widget = <<<WIDGET
    <p>Good Morning {$name}</p>
WIDGET;

Solution 3:

Have you considered tried quoting the quotes Such as \\\"?

After one step, this will usually become \", and after the second step ".

Anyway, generating (javascript) code inside (html) code from (php) code is bound to become messy. Consider using a templating system, or separating concerns.

Solution 4:

Another trick is defining the strings in javascript before putting them into the onchange, then using single quotes there

<scripttype='text/javascript'><!--
var a = 'a';
var b = 'b';
--></script>
...
<... onchange='function(a, b)'>

Post a Comment for "Quoting Quotation Marks"