2017-09-19 10 views
0

申し訳ありませんが質問を繰り返していますが、私はpreg_replace関数を使用して個別のケースを持っています。これは、それらの値に、その名前からテンプレート内の変数($ VARS)($データ)を交換する機能ですpreg_replaceからpreg_replace_callbackへの変換

function replace_vars($data, array $vars) { 
    return preg_replace(array('/\{\{([a-zA-Z0-9_]+)\}\}/e', '/\{\{([a-zA-Z0-9_]+):(\d+)\}\}/e'), 
     array("\$vars['\\1']", "\$vars['\\1'][\\2]"), $data); 
} 

$テンプレートフラグメント

<td>{{name}}</td> 
<td>{{active_items}}</td> 
<td>{{percents}} %</td> 

関数呼び出し

$report = ''; 
$f['name'] = 'some name'; 
$f['active_items'] = 237; 
$f['percents'] = 'some name'; 
$report .= $mailer->replace_vars($template, $f); 

方法それはできますか?

答えて

0

私があなたをよく理解すれば、それは簡単です。

preg_replace_callback([...], function($matches) use ($vars) { 
    # Use ($vars) will inherit it from the current scope 
    $v = $vars[$matches[1]]; # Select item with key of capturing group 1 
    if ($matches[2]) { # If group 2 was matched 
    $v = $v[$matches[2]]; # Select contents of item with the same key as it's value from the previous item 
    } 
    return $v; # Replace it. 
}, [...]); 

グループ2がマッチした場合は$var[\1]または$var[\1][\2]ですべての試合に置き換えられます。

関連する問題