我是编程新手,我不知道使用这种预期编程的函数或方法。是这样的
PHP FILEPHP 上的预定义变量
<?php $a=1 ;$b=2;$c=3; $d=4; ?>
HTML FILE在文本区域输入在文本区域的顶部写入
使用代码{a}生成1,{b}生成2,{c}生成3,{d} 生成4个
所以当用户在下面输入时:
I wanna buy {a} apple, {b} mangos, {c} grapes and {d} oranges
OUTPUT在php上进行echo时,解析{代码}将被引用到预定义的变量
I wanna buy 1 apple, 2 mangos, 3 grapes and 4 oranges
有人可以帮我使用什么库或函数吗?感谢
也许一个简单的preg_replace_callback可以完成
<?php
$values = array('a'=>1, 'b'=>2, 'c'=>3, 'd'=>4); // I don't want to litter the global namespace -> array
$userinput = 'I wanna buy {a} apple, {b} mangos, {c} grapes and {d} oranges';
$result = preg_replace_callback(
'!{([a-z])}!', // limited to one small-case latin letter
function ($capture) use ($values) {
// for each match this function is called
// use($values) "imports the array into the function
// whatever this function returns replaces the match in the subject string
$key = $capture[1];
return isset($values[$key]) ? $values[$key] : '';
},
$userinput
);
echo $result;
打印
I wanna buy 1 apple, 2 mangos, 3 grapes and 4 oranges