0

Good day.

I use SprintF function in my localisation system for a custom script, but I would like to have also enum values which would spare me a lot of code.

Right now I do

$string = 'Some localisation string with %s and %s variables.';
$qwe = sprintf($string,'xxx', 'yyy'); //returns: Some localisation string with xxx and yyy variables.

It's good for simple values, but I have a lot of situations where I would like to use enumerable things.

So, I would like to have something like this

$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

Is it possible? Is there any buildin function that can be used? Or do I have to implement it myself? If so, maybe there are already some solutions or libraries?

PS - please don't suggest me to use template engines. I only need this particular functionality.

NewProger
  • 2,945
  • 9
  • 40
  • 58

1 Answers1

1

There are no such bulidin function, you need to write one yourself.

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);
}
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Wow, I didn't expect someone to actually write the function for me! :) Thank you very much for your help! – NewProger Sep 02 '12 at 05:33
  • Oh, and btw, just in case. Do you know some string parsing libraries that would parse strings similar to how Smarty does it? – NewProger Sep 02 '12 at 05:33
  • @NewProger For simple use, you could check this function.http://stackoverflow.com/questions/7980741/efficient-way-to-replace-placeholders-with-variables/7980830#7980830 – xdazz Sep 02 '12 at 05:35