簡體   English   中英

正確的方法來逃避包含PHP變量的HTML字符串中的引號

[英]Proper Way to Escape Quotes in HTML string that includes PHP variables

我正在編寫一串需要接收一些PHP變量的HTML。 但是,我似乎無法正確地逃避雙引號。

嘗試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>

在這里,你只需要先嘗試一步,你只需要從單個引號中移出雙引號。

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

在這里你可以看到一個實時樣本

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

我總是建議不要回顯HTML,所以請這樣做

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

如果你停止PHP,你可以編寫HTML,它將正常工作。 在HTML內部,您可以使用簡寫的php回聲來獲取HTML中需要的任何數據

這樣做的一個主要優點是您的編輯器將正確語法突出顯示所有代碼(包括HTML)

讓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>";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM