【问题标题】:Proper Way to Escape Quotes in HTML string that includes PHP variables在包含 PHP 变量的 HTML 字符串中转义引号的正确方法
【发布时间】:2016-03-18 20:16:16
【问题描述】:

我正在编写一个 HTML 字符串,它需要接收我的一些 PHP 变量。但是,我似乎无法正确转义双引号。

尝试 1:

$html .= '<span class="badge"><a href="#" style="color:orange"><span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction(\''.$configType.'\')"></span></a></span>';

结果:

<span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction(\' project\')"=""></span>

尝试 2:

$html .= '<span class="badge"><a href="#" style="color:orange"><span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction('.'$configType'.')"></span></a></span>';

结果:

<span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction(project)"></span>

关闭,但应该是'project'


期望的结果:

<span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction('project')"></span>

【问题讨论】:

  • 奇怪,我测试时你的第一次尝试成功了。

标签: php html string variables escaping


【解决方案1】:

来了,第一次尝试时你离你更近了一步,你只需要将双引号从单引号中移出。

$html .= '<span class="badge"><a href="#" style="color:orange"><span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction("'.$configType.'")"></span></a></span>';

Here you can see a live sample

【讨论】:

  • 呵呵呵呵,你差不多就在那儿
【解决方案2】:

HEREDOC

$HTML = <<<_E_
<span class="badge"><a href="#" style="color:orange"><span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction("$configType")"></span></a></span>
_E_;

NOWDOCsprintf 的专家模式:

$frame = <<<'_E_'
<span class="badge"><a href="#" style="color:orange"><span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction("%s")"></span></a></span>
_E_;
$HTML = sprintf($frame, $configType);

【讨论】:

    【解决方案3】:

    我始终建议不要回显 HTML,而是这样做

    <?php
    $configType = 'project';
    // etc ...
    ?>
    <span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction(<?= $configType ?>)"></span>
    

    如果你停止 PHP,你可以编写 HTML,它会正常工作。在 HTML 中,您可以使用简写 php echos 将所需的任何数据放入 HTML

    这样做的一个主要优点是您的编辑器将正确地语法高亮所有代码(包括 HTML)

    【讨论】:

      【解决方案4】:

      通过让 PHP 完成变量插值的工作,您可以省去一些麻烦。将双引号放在字符串的末尾,并将其他引号更改为不连接的单引号:

      $html .= "<span class='badge'><a href='#' style='color:orange'><span class='glyphicon glyphicon-arrow-up' aria-hidden='true' onclick='sendToProduction('$configType')'></span></a></span>";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多