2014-05-19 205 views
-3

試圖讓HTML代碼使用回聲工作表單輸入,回聲反斜槓

這個工程爲html:

<input type="text" name="ordernum" value="<?= isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : '' ?>" /> 

但是當我轉義反斜線值(我曾經嘗試幾十個組合和閱讀很多在stackoverflow,但仍然不能解決它)我得到意想不到的T_STRING錯誤。

echo ' <input type="text" name="ordernum" value=\'= isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : '' \' />'; 
+4

你不能只寫任意P HP代碼*位於字符串文字*的中間。 – Quentin

回答

0

由於Quentin has commented

你不能只寫任意PHP代碼字符串字面

這是因爲$_POST['ordernum']部分的中間。

它再這樣寫:

$val = isset($_POST["ordernumW]) ? htmlspecialchars($_POST["ordernum"]) : ""; 

echo "<input type='text' name='ordernum' value='$val' />"; 
0

你不能在一個字符串使用任意代碼。首先在一個變量中賦值並在echo語句中使用該變量。

$orderNum = isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : ''; 
echo ' <input type="text" name="ordernum" value="'.$orderNum.'" />'; 
+1

三元條件在字符串定義中是完全有效的。你應該刪除''標籤並正確拼接;-) – svvac

+0

這個解決方案適用於我:) – botch

+1

@ user3556674好吧,接受這個答案並關閉這個問題。 – Manibharathi

0

您需要\逃避可能結束你的字符串中的字符(即專門字符串分隔符"')。

這兩行工作:

echo "<input type=\"text\" name=\"ordernum\" value=\"" . (isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : '') . "\" />"; 
echo '<input type="text" name="ordernum" value="' . (isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : '') . '" />'; 
+0

已經說過[這裏](http://stackoverflow.com/questions/23738996/echo-a-form-input-with-backslashes#comment36492633_23738996)你不能在字符串中使用任意條件 – krishna

+0

這段代碼是完全有效的。三元條件評估爲$ _POST ['ordernum']'的HTML轉義版本或與第一部分連接的空字符串。你不能在字符串定義中使用'if'語句,但是沒有什麼能夠阻止你連接文字,函數結果或三元條件。 – svvac

0

這是它應該是什麼:

echo('<input type="text" name="ordernum" value="'.(isset($_POST['ordernum'])?htmlspecialchars($_POST['ordernum']):'').'">'); 

您可以使用一個句號來連接字符串,所以你應該結束的第一部分字符串,添加一個句號,然後是動態值,另一個句號,然後是字符串的其餘部分。

所以在你的字符串,你在做什麼錯在這裏:

value=\'= isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : '' \' 

像這樣:

"first part of string".$myvariable."last part of string"; 

你只需要逃離該字符串包含在報價類型也通過:

"I need to escape this \" but not this ' " 
'I need to escape this \' but not this " ' 
0
$val = isset($_POST['ordernum']) ? htmlspecialchars($_POST['ordernum']) : ''; 

echo '<input type="text" name="ordernum" value="'. $val. '" />'; 
+0

這對三元if語句有什麼好處? – Luke

+0

現在解決了這個問題。 –