5

I have a PHP string that contains single and double quotes, but am having a rough time getting it escaped properly. Even tried online quotify sites, but their result errors also.

$confirmation .= '<a title="Share on Facebook" target="_blank" href="javascript: void(0)" onclick="window.open('http://www.facebook.com/sharer.php?u=http%3A%2F%2Fmydomain.com%2Fquiz%2F','sharer','toolbar=0,status=0,width=548,height=325');" class="">Share on Facebook</a>';

I don't think the double quotes need to be escaped. Still, all of my attempts result in HTTP 500 when loading the page.

How do the single quotes inside this string get escaped?

random_user_name
  • 23,924
  • 7
  • 69
  • 103
rwkiii
  • 5,368
  • 17
  • 60
  • 102

2 Answers2

8

To escape nested quotes in PHP, use the \

 $confirmation .= '<a title="Share on Facebook" target="_blank" href="javascript: void(0)" onclick="window.open(\'http://www.facebook.com/sharer.php?u=http%3A%2F%2Fmydomain.com%2Fquiz%2F\',\'sharer\',\'toolbar=0,status=0,width=548,height=325\');" class="">Share on Facebook</a>';

For a complicated case with lots of quotes, it may be more readable and practical to use a heredoc:

$confirmation .= <<<EOT
  <a title="Share on Facebook" target="_blank" href="javascript:void(0)" onclick="window.open('http://www.facebook.com/sharer.php?u=http%3A%2F%2Fmydomain.com%2Fquiz%2F','sharer','toolbar=0,status=0,width=548,height=325');" class="">Share on Facebook</a>
EOT;
Brandon Horsley
  • 7,246
  • 25
  • 27
  • 1
    You are correct. The code is in functions.php - I had another window open in my editor and got totally confused - twice. :S It is PHP. – rwkiii Jul 28 '16 at 21:18
  • 2
    YAY for heredoc Could not agree more, for convoluted vars where lots of escaping would be needed, heredoc syntax is the way to go. – Duane Lortie Jul 28 '16 at 21:20
0

$confirmation .= '<a title="Share on Facebook" target="_blank" href="javascript: void(0)" onclick="window.open(\'http://www.facebook.com/sharer.php?u=http%3A%2F%2Fmydomain.com%2Fquiz%2F\',\'sharer\',\'toolbar=0,status=0,width=548,height=325\');" class="">Share on Facebook</a>';

Jacob Manser
  • 122
  • 6