简体   繁体   中英

single and double quotes in php variable

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>';

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 :)

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.

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>';

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM