【问题标题】:single and double quotes in php variablephp变量中的单引号和双引号
【发布时间】:2013-04-24 16:39:04
【问题描述】:

我怎样才能将这段代码与所有单引号和双引号结合起来。 我已经尝试了几种组合,但我无法使其工作。 这是我最后一次尝试所以请帮忙。

处理长字符串时有什么好的方法?

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

【问题讨论】:

  • 我认为问题出在style 属性部分。后台url的开引号关闭style属性的开引号。也许您应该按照下面@Jeffrey 的回答,将您的样式表分开而不是使其内联:)
  • 这里有 2 个注意事项:您在 url( 上缺少结尾 ),而且看起来很奇怪,您不需要在 url 周围加上任何引号

标签: php javascript string quotes string-concatenation


【解决方案1】:

我会将您的样式移动到外部样式表以使其更短,然后将字符串中的 "\"" 等引号转义为 "。

$html .="<a href=\"\" onClick=\"$.ajax({type: \"POST\",url: \"delete_pic.php\",data:{id:\".$row["\id\"].",var:\"V\"},cache: false});\" class=\"mystyle\"></a>";

这没有经过测试,因为我没有你的代码:)

【讨论】:

  • 是的,我明白,但这只是一个创建的元素,所以我没有把它放在外部样式表中。
  • 我以前也这样做过 :) 但它总是会回来咬你 :)
【解决方案2】:

最好的解决方案是使用HEREDOC,这完全消除了在 PHP 级别转义任何引号的需要:

$html .= <<<EOL
<a href="onclick('\$.ajax({ etc.....

EOL;

请注意,您仍然会受到您在 heredoc 中嵌入的任何语言的引用需求的约束。但至少您不必担心由于引号不平衡/未转义而导致 PHP 语法错误。

【讨论】:

    【解决方案3】:

    我遵循的规则是:php字符串用单引号封装,所以html的属性用双引号。
    属性中的任何引号都必须是转义的单引号 \'

    所以:

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

    【讨论】:

      【解决方案4】:

      您可能应该只转义其他双引号内的双引号(如果有意义的话)。 :)

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

      那(或类似的东西)应该可以工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-02
        • 1970-01-01
        • 2012-01-25
        • 2014-06-28
        相关资源
        最近更新 更多