2012-03-20 36 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