我已经设置了将 {1}
替换为 $param1
的功能,如下所示:
<?php
$lang = '{1} say not exist!';
$replaceParam = 'aaa';
function languageParam($value, $param)
{
$value = preg_replace("/\{(.+?)\}/s", $param, $value);
return $value;
}
echo languageParam($lang, $replaceParam );
我想知道是否可以用这种特定格式替换字符串:
{numbers}
像这样:
<?php
$lang = '{1} say {2} not exist!';
$param = array(
'1' => 'aaa',
'2' => 'bbb'
);
我的意思是,如何使函数能够对输入数组进行计数并用数字代替它们?
例如:
<?php
$lang = '{1} say {2} {3} {4}'; //maybe have {5}, {6}...etc
$param = array(
'1' => 'aaa',
'2' => 'bbb',
'3' => 'ccc',
'4' => 'ddd'
//and '5', '6'...etc
);
它将输出
aaa say bbb ccc ddd //....and more
有可能吗?还是可以,但是要花费很多时间来计算和搜索字符串?
答案 0 :(得分:1)
您要遍历数组,然后使用数组的索引对要替换的值进行字符串替换:
<?php
$lang = '{1} say {2} {3} {4}';
$param = array(
'1' => 'aaa',
'2' => 'bbb',
'3' => 'ccc',
'4' => 'ddd'
);
foreach($param as $index => $p) {
$lang = str_replace('{' . $index . '}', $p, $lang);
}
echo $lang; //aaa say bbb ccc ddd
我个人会使用方括号...
<?php
$lang = '[1] say [2] [3] [4]';
$param = array(
'1' => 'aaa',
'2' => 'bbb',
'3' => 'ccc',
'4' => 'ddd'
);
foreach($param as $index => $p) {
$lang = str_replace("[$index]", $p, $lang);
}
echo $lang; //aaa say bbb ccc ddd
您可以避免随后断开字符串。
带有字符串索引和数字:
<?php
$lang = '{char_1} say {2} {char_3} {4}';
$param = array(
'char_1' => 'aaa',
'2' => 'bbb',
'char_3' => 'ccc',
'4' => 'ddd'
);
foreach($param as $index => $p) {
$lang = str_replace('{' . $index . '}', $p, $lang);
}
echo $lang; //aaa say bbb ccc ddd