Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape single quotes in string containing single and double quotes

Tags:

php

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?

like image 859
rwkiii Avatar asked Jul 28 '16 21:07

rwkiii


1 Answers

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;
like image 152
Brandon Horsley Avatar answered Nov 14 '22 22:11

Brandon Horsley