2012-03-20 190 views
0

我有一個字符串,可以有簡單的模板。我有一個數組,其中包含replacemenet的值。目前我正在循環做。但我想將其更改爲preg_replace。你可以幫我嗎?用數組值替換字符串中的模板

例子:

$values = array(
    'id' => 120, 
    'name' => 'Jim' 
); 
$string = 'Hello <!name!>. Your ID is <!id!>'; 
$output = preg_replace(...); // Hello Jim. Your ID is 120 

另外的preg_replace應該工作不僅與標識和名稱,但與其他任何按鍵。謝謝。

+0

我可能會使用'preg_replace_callback'和閉合。 – 2012-03-20 09:34:21

回答

2

像下面這樣的東西?

<?php 
$values = array(
    'id' => 120, 
    'name' => 'Jim' 
); 
$string = 'Hello <!name!>. Your ID is <!id!>'; 

function foo($val) { 
     return '/<!' . $val . '!>/'; 
} 

echo preg_replace(array_map('foo', array_keys($values)), array_values($values), $string); 

如果整個事情是一個類:

class Template { 
     static function bar($val) { 
       return '/<!' . $val . '!>/'; 
     } 

     function render($values, $string) { 
       echo preg_replace(array_map(array('Template', 'bar'), array_keys($values)), array_values($values), $string); 
     } 
} 

$values = array(
    'id' => 120, 
    'name' => 'Jim' 
); 
$string = 'Hello <!name!>. Your ID is <!id!>'; 
$T = new Template(); 
$T->render($values, $string); 
+0

謝謝。好東西。我可以使用類方法而不是array_map()的函數嗎? – pltvs 2012-03-20 09:34:35

+0

肯定會編輯 – 2012-03-20 09:36:14

+0

編輯我的回答:),希望有幫助 – 2012-03-20 09:39:24