您好。
我在本地化系统中使用SprintF函数作为自定义脚本,但我也希望有枚举值,这样可以节省大量代码。
现在我做
$string = 'Some localisation string with %s and %s variables.';
$qwe = sprintf($string,'xxx', 'yyy'); //returns: Some localisation string with xxx and yyy variables.
它适用于简单的值,但我在很多情况下都希望使用可枚举的东西。
所以,我想要像这个一样的东西
$string = 'Some string %{qwe,zxc,ddd,yyy} blah blah';
$qwe = someFunction($string,1); //would return: Some string zxc blah blah
$qwe = someFunction($string,3); //would return: Some string yyy blah blah
有可能吗?有什么内置函数可以使用吗?还是我必须自己实施?如果是这样,也许已经有一些解决方案或库了?
PS-请不要建议我使用模板引擎。我只需要这个特殊的功能。
没有这样的bulidin函数,您需要自己编写一个。
function someFunction($string, $index) {
return preg_replace_callback('/%'{([^'}]*)'}/', function($matches) use ($index) {
$values = explode(',', $matches[1]);
return isset($values[$index - 1]) ? $values[$index - 1] : $matches[0];
}, $string);
}