2016-03-18 12 views
4

PHP変数の一部を取り入れる必要があるHTML文字列を書いています。しかし、二重引用符を正しくエスケープすることはできません。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> 
+2

私はそれをテストしたときに最初の試みがうまくいきました。 – Xposedbones

答えて

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

Here you can see a live sample

+0

AHHHありがとう!それは愚かなものだったと考えた –

+0

Heheheええ、そこにalmoustだった – Fabio

0

私は常にHTMLをエコーないことをお勧めしますので、あなたがHTMLを書くことができ、それが正常に動作するPHPを停止した場合、代わりにこの

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

を行います。 HTMLの中にあなたがHTMLに必要なものは何でもデータを取得するために、短手PHPのエコーを使用することができます

これを行うの1つの主要な利点は、あなたのエディタます(HTMLを含む)を正しく構文強調表示、すべてのコード

1

HEREDOC

NOWDOCsprintf
$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_; 

エキスパートモード:

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

あなたCOU 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>"; 
関連する問題