问题
How can I combine this code with all single and double quotes as it should be. I have tried several combinations and I can't make it work. This one is my last try so please help.
What would be a good approach when working with long strings?
$html .='<a href="" onClick="$.ajax({type: "POST",url: "delete_pic.php",data:{id:"'.$row['id'].'",var:"V"},cache: false});" style="background:url("images/icons/delete.png" 50% -19px no-repeat;width:16px;height:16px;float:left;margin-left:10px;margin-top: 6px;"></a>';
回答1:
I follow the rule of: php strings are encapsulated in single quote, so attributes of html are in double quotes.
Any quote in the attribute must be an escaped single quote \'
so:
$html .='<a href="" onClick="$.ajax({type: \'POST\',url: \'delete_pic.php\',data:{id:\''.$row['id'].'\',var:\'V\'},cache: false});" style="background:url(\'images/icons/delete.png\' 50% -19px no-repeat;width:16px;height:16px;float:left;margin-left:10px;margin-top: 6px;"></a>';
回答2:
I would move your styles to an external stylesheet to make it shorter, and then just escape the quotes like "\"" for " in the string.
$html .="<a href=\"\" onClick=\"$.ajax({type: \"POST\",url: \"delete_pic.php\",data:{id:\".$row["\id\"].",var:\"V\"},cache: false});\" class=\"mystyle\"></a>";
This was not tested because I don't have your code :)
回答3:
Best solution is to use HEREDOC, which completely eliminates the need for ANY quote escaping at the PHP level:
$html .= <<<EOL
<a href="onclick('\$.ajax({ etc.....
EOL;
Note that you'll still be bound by the quoting needs of whatever language(s) you're embedding in the heredoc. But at least you won't have to worry about causing a PHP syntax error because of unbalanced/unescaped quotes.
回答4:
You should probably just escape the double-quotes inside the other double-quotes (if that makes sense). :)
$html .='<a href="" onClick="$.ajax({type: \"POST\",url: \"delete_pic.php\",data:{id:\"'.$row['id'].'\",var:\"V\"},cache: false});" style="background:url(\"images/icons/delete.png\" 50% -19px no-repeat;width:16px;height:16px;float:left;margin-left:10px;margin-top: 6px;"></a>';
That (or something similar) should work.
来源:https://stackoverflow.com/questions/16197550/single-and-double-quotes-in-php-variable