这是非常基本的,但我错过了一个拼图。
我有一个多维PHP数组 - 除其他外 - 包含一些字符串。我想基于PHP中的转换表或数组来翻译此数组中的特殊字符串。
$r = array(
0 => 'something',
1 => array(
'othertext' => '1000 {{animals}} and {{cars}}',
'anytext' => '400 {{cars}}',
)
);
在$ r中,现在我想用另一个存储在单独数组中的字符串替换{{animals}}。
这是:
$translations = array(
'animals' => array('Tiere','animaux','bestie'),
'cars' => array('Autos','voitures','macchine'),
);
现在让我们设置我们想要查找的语言/列
$langId = 0;
现在,取$ r,查找包含在{{}}中的所有密钥,在$ translate中查找它们并用密钥[$ langId]替换它们,所以作为回报我们得到:
$r = array(
0 => 'something',
1 => array(
'othertext' => '1000 Tiere',
'anytext' => '400 Autos',
)
);
嗯......怎么做的?
PS:标记{{}}是随机的,可能是任何强大的
答案 0 :(得分:2)
我能够使用以下代码获得您期望的输出。尝试一下,告诉我它是否适合你:
<?php
$r = array(
0 => 'something',
1 => array(
'othertext' => '1000 {{animals}} and {{cars}}',
'anytext' => '400 {{cars}}',
)
);
$translations = array(
'animals' => array('Tiere','animaux','bestie'),
'cars' => array('Autos','voitures','macchine'),
);
$langId = 0;
$pattern = "/\{\{[a-zA-Z]+\}\}/";
for($t=0; $t<count($r); $t++) {
$row = $r[$t];
if(!is_array($row))
continue;
foreach($row as $key=>$value) {
if(preg_match_all($pattern, $value, $match, PREG_SET_ORDER)) {
for($i = 0; $i < count($match); $i++) {
//remove {{ & }} to get key
$k = substr($match[$i][0], 2, strlen($match[$i][0])-4);
$replacer = $translations[$k][$langId];
$value = str_replace($match[$i][0], $replacer, $value);
$r[$t][$key] = $value;
}
}
}
}
?>