How to escape quotes in PHP? [closed]

2019-03-06 05:50发布

问题:

I have that code:

<a href="#" onclick="$('#two').html('<img src=\'http://willstern.com/web/wp-content/uploads/2011/06/jquerylogo2.png\' />');return false;">Add an Img</a>

and i don't know how to place it here echo ' code ' ;

回答1:

This will work (tested)

<?php 

  echo "<a href=\"#\" onclick=\"$('#two').html('<img src=\'http://willstern.com/web/wp-content/uploads/2011/06/jquerylogo2.png\' />');return false;\">Add an Img</a>";

?>

To escape single or double quotes in php you add a backslash just before \' \" see the documentation.

Ah yes and the same goes for jQuery see the documentation.

As you are using jQuery I would recommend that you separate your JS from your HTML a little, you could write the same code like this.

<a href="#" class="add_an_image">Add an Image</a>

<script>

  $('.add_an_image').click(function(){

    $('#two').html('<img src="http://willstern.com/web/wp-content/uploads/2011/06/jquerylogo2.png" />');
    return false;

  });

</script>


回答2:

Try this:

$code = "<a href=\"#\" onclick=\"$('#two').html('<img src=\'http://willstern.com/web/wp-content/uploads/2011/06/jquerylogo2.png\' />');return false;\">Add an Img</a>";

echo $code;


回答3:

echo "<a href=\"#\" onclick=\"$('#two').html('<img src=\'http://willstern.com/web/wp-content/uploads/2011/06/jquerylogo2.png\' />');return false;\">Add an Img</a>";


回答4:

Also you can try the heredoc syntax:

<?php
$str = <<<EOD
<a href="#" onclick="$('#two').html('<img src=\'http://willstern.com/web/wp-content/uploads/2011/06/jquerylogo2.png\' />');return false;">Add an Img</a>
EOD;
echo $str;


标签: php jquery echo