2013-11-28 48 views
5

我試圖在使用sprintf但不合格時在不同位置使用相同的值。sprintf多次使用相同的值

<?php 

$score = 50; 
$percent = 10; 

$str = "Hello: You scored %s (%s%%). Your score is %2$s %%"; //Problem is here %2$s 

echo sprintf($str,$score,$percent); 
?> 

我得到這個錯誤:Notice: Undefined variable: s in C:\web\apache\htdocs\sprintf.php on line 6 Warning: sprintf(): Too few arguments in C:\web\apache\htdocs\sprintf.php on line 8

回答

6

使用單引號代替雙引號:當你在它使用單引號的字符串和號碼的所有你的論點

$str = 'Hello: You scored %s (%s%%). Your score is %2$s %%'; 

變量雙引號內擴展,所以$s被視爲一個變量,而不是格式化選項。

如果你想使用雙引號,你可以擺脫美元符號:

$str = "Hello: You scored %s (%s%%). Your score is %2\$s %%"; 
+0

但我需要這些雙引號。他們在那裏有一個目的。 – jmenezes

+0

好的。我在'$'之前放了一個'\',現在沒問題。 – jmenezes

+0

您也可以使用連接而不是插值來在字符串中執行變量替換。 – Barmar

1

雙引號字符串內部的$用於變量插值,PHP正在尋找變量$s這裏。

'Hello: You scored %1$s (%1$s%%). Your score is %2$s %%' 
+0

我需要那些雙引號。那裏也有變數。不在這裏顯示,但在腳本中。 – jmenezes

+0

那麼你需要轉義''''這意味着字面'''s:''...%1 \ $ s ...「'。 – deceze

+0

啊!是!我做到了。謝謝 – jmenezes