【发布时间】:2018-01-24 06:43:24
【问题描述】:
我有 2 个数组,都包含人名和水果名。两个数组都是动态生成的。
$persons = array(0 =>'John', 1 => 'Alan', 2 => 'Ninja');
$fruits = array(0 =>'apple', 1 => 'mango', 2 => 'banana', 3 => 'kiwi');
还有一个字符串,我想根据模式提供的键对其执行替换。
$str = "[person1] eats [fruit1]";
$str2 = "These [fruit2] belongs to [person3] and his friends";
我希望我的输出像
$str = "John eats apple";
$str2 = "These mango belongs to Ninja and his friends";
我想搜索模式并从模式[person*] 和[fruit*] 中获取* 的值,其中* 是动态生成的字符串。
编辑 1
我创建了一个函数
function replaceable_string($str, $elements, $pattern, $match="*"){
foreach($elements as $index => $element){
$index++;
$new_pattern = str_replace($match, $index, $pattern);
$str = str_replace($new_pattern, $element, $str);
}
return $str;
}
这样传递的值
$str = replaceable_string($str, $persons, '[person*]');
$str = replaceable_string($str, $fruits, '[fruit*]');
echo $str;
我不知道这有多高效。
或者有没有其他最好的方法来实现这一点?
【问题讨论】:
-
您是否考虑过“合适的”模板系统