2012-01-13 32 views
1

我需要一個函數,用正確的變量替換「{}」中的每個variable_name。 事情是這樣的:如何用實際值替換佔位符?

$data["name"] = "Johnny"; 
$data["age"] = "20"; 

$string = "Hello my name is {name} and I'm {age} years old."; 

$output = replace($string, $data); 
echo $output; 

//outputs: Hello my name is Johnny and I'm 20 years old. 

我知道有框架/引擎這一點,但我不希望有安裝一堆文件只是爲了這個。

回答

11

您可以用/e改性劑preg_replace做到這一點最容易:

$data["name"] = "Johnny"; 
$data["age"] = "20"; 

$string = "Hello my name is {name} and I'm {age} years old."; 

echo preg_replace('/{(\w+)}/e', '$data["\\1"]', $string); 

See it in action

您可能想要自定義與替換字符串匹配的模式(這裏是{\w+}:一個或多個字母數字字符或大括號之間的下劃線)。把它變成一個函數是微不足道的。

+0

不錯的解決方案,+1。雖然我會用'[^ ​​\}] +'而不是'\ w' – zerkms 2012-01-13 05:18:11

2

在這裏你去:

$data["name"] = "Johnny"; 
$data["age"] = "20"; 

$string = "Hello my name is {name} and I'm {age} years old."; 

foreach ($data as $key => $value) { 
$string = str_replace("{".$key."}", $value, $string); 
} 

echo $string; 
+1

哇,我覺得沒有想到這一點很愚蠢。 – user1091856 2012-01-13 05:19:25

0
$string = "Hello my name is {$data["name"]} and I'm {$data["age"]} years old."; 

會做你想要什麼。如果它不適合你,請嘗試類似循環與正則表達式,像這樣

for ($data as $key=>$value){ 
    $string = preg_replace("\{$key\}", $value, $string); 
} 

未經測試,您可能需要諮詢文檔。

+0

在這裏使用'preg_replace'而不是'str_replace'的任何特定原因? – zerkms 2012-01-13 05:19:22

0

您可以嘗試vsprintf它有稍微不同的語法

$string = 'hello my name is %s and I am %d years old'; 

$params = array('John', 29); 

var_dump(vsprintf($string, $params)); 
//string(43) "hello my name is John and I am 29 years old" 
0

我一直的strtr風扇。

$ php -r 'echo strtr("Hi @name. The weather is @weather.", ["@name" => "Nick", "@weather" => "Sunny"]);' 
Hi Nick. The weather is Sunny. 

另一個優點是你可以定義不同的佔位符前綴類型。這是Drupal如何做到的; @表示一個字符串被轉義爲安全輸出到網頁(以避免注入攻擊)。 format_string命令會循環使用參數(例如@name@weather),如果第一個字符是@,則該值將使用check_plain

也在這裏回答:https://stackoverflow.com/a/36781566/224707