この例はネストの背後にある目的を示していないため、例のネストを理解しているかどうかはわかりません。入力例は非常に簡単です
'This is my test {@a} {@b} string.'
str_replace で配列を使用すると、これを非常に簡単かつ迅速に処理できます。
$aVars = array('{@a}' => 'hello', '{@b}' => 'world');
$sString = 'This is my test {@a} {@b} string.';
echo str_replace(array_keys($aVars), array_values($aVars), $sString);
それは私たちに与えます
これは私のテスト用の Hello World 文字列です。
さて、この再帰関数はそれほど難しくありませんが、それがどれほど役立つかはわかりません。これが実際の例です:
function template($sText, $aVars) {
if (preg_match_all('/({@([^{}]+)})/',
$sText, $aMatches, PREG_SET_ORDER)) {
foreach($aMatches as $aMatch) {
echo '<pre>' . print_r($aMatches, 1) . '</pre>';
if (array_key_exists($aMatch[2], $aVars)) {
// replace the guy inside
$sText = str_replace($aMatch[1], $aVars[$aMatch[2]], $sText);
// now run through the text again since we have new variables
$sText = template($sText, $aVars);
}
}
}
return $sText;
}
その print_r は一致がどのように見えるかを示すので、関数のペースをたどることができます。では、試してみましょう...
$aVars = array('a' => 'hello', 'b' => 'world');
$sStringOne = 'This is my test {@a} {@b} string.';
$sStringTwo = 'This is my test {@a{@b}} string.';
echo template($sStringOne, $aVars) . '<br />';
最初の結果:
これは私のテスト用の Hello World 文字列です。
では、弦 2 を試してみましょう
echo template($sStringTwo, $aVars) . '<br />';
2 番目の結果:
これは私のテスト {@aworld} 文字列です。
それはあなたが探しているものかもしれません。aworld
明らかに、これが再帰的に機能するには変数が必要です...
$aVars = array('a' => '', 'b' => '2', 'a2' => 'hello world');
echo template($sStringTwo, $aVars) . '<br />';
そして私たちの結果。
これは私のテスト用の Hello World 文字列です。
そして、再帰を楽しむために...
$aVars = array('a3' => 'hello world', 'b2' => '3', 'c1' => '2', 'd' => '1');
$sStringTre = 'This is my test {@a{@b{@c{@d}}}} string.';
echo template($sStringTre, $aVars) . '<br />';
これは私のテスト用の Hello World 文字列です。
これがあなたが求めているものかどうかわからない...