我有这个文本数组
$text = array( "T02" => array( 'EN' => 'English text for T02'),
"T03" => array( 'FR' => 'Texte anglais pour T03'));
$language = "FR";
$testtext = "Translated text: {#text['T03'][$language]}";
我需要#here,因为我通过函数从数据库中获取此文本。
所以我需要用$
替换de#// This will work, but I need 'T03' and $language to be variable:
$output = str_replace("{#text['T03'][$language]}","{$text['T03'][$language]}",$testtext);
echo $output;
// This won't work:
$output = str_replace("#text","$text",$testtext);
echo $output; // I get ==> Translated text: {Array['T03'][FR]}
如何替换" {#text [' .. var1 ..'] [.. var2 ..] }" ==> {$ text [' .. var1 ..'] [.. var2 ..]}?
答案 0 :(得分:0)
使用preg_replace
<?php
$text = "{#text['..var1..'][..var2..]}";
$pattern = '/{#(.*)/';
echo preg_replace($pattern, '{\$$1', $text);
<?php
$text = array( "T02" => array( 'EN' => 'English text for T02'),
"T03" => array( 'FR' => 'Texte anglais pour T03'));
$language = "'FR'";
$testtext = "Translated text: {#text['T03'][$language]}";
$pattern = '/{#(?P<varName>\S+)\[\'(?P<someKey>\S+)\'\]\[\'(?P<langKey>\S+)\'\]}/';
$callback = function($match)use($text){
return $text[$match['someKey']][$match['langKey']];
};
echo preg_replace_callback($pattern,$callback, $testtext);
<?php
$text = array( "T02" => array( 'EN' => 'English text for T02'),
"T03" => array( 'FR' => 'Texte anglais pour T03'));
$language = "'FR'";
$testtext = "Translated text: {#text['T03'][$language]}";
$pattern = '/{#(.*?)}/';
echo eval('return "'.preg_replace($pattern, '{\$$1}', $testtext).'";');