panthro
panthro

Reputation: 24099

Quotes within quotes - as a string?

I have a PHP string:

$str = '';

I need to have some HTML in this, but the HTML has 'quotes within quotes'. How would one deal with the situation?

The HTML is:

data-setup="{'example_option':true}"

Upvotes: 0

Views: 1911

Answers (3)

Max
Max

Reputation: 6811

Looks like you want to pass some data from PHP to a view through the data-attribute. I would recommend you use json_encode and build you're data as a normal PHP array rather than worrying about escaping quotes or other nasty stuff.

<html>
    <head>
        <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    </head>
    <body>
        <?php

            $data = array(
                  'example_option' => true,
                  'some_html'      => '<b>"Hello & good day!"</b>',
                );

            // avoid escaping from the JS parser
            $str = json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
            ?>

        <a data-setup='<?php echo $str; ?>' href="#">This link has awesome data</a>
    </body>
</html>

Then you can just access access the data attribute very easily (I did make a big assumption here that you are using jQuery).

Upvotes: 0

senK
senK

Reputation: 2802

You can also use HEREDOC

<?php
$html = <<<EOD
        data-setup="{'example_option':true}"
EOD;

echo $html;

Upvotes: 0

Ole Haugset
Ole Haugset

Reputation: 3797

To deal with quotes inside quotes, you need to escape them like this:

echo "<a href=\"somelink.html\">Link</a>";

simply put:

\" tells php to simply echo out the " as a quote instead of handling it as a part of the code.

Your string:

$string = "data-setup=\"{'example_option':true}\""
echo $string;
// Output:
data-setup="{'example_option':true}"

Upvotes: 1

Related Questions