0

I have following python code to format the string,

endpoint = '/uri/{id}'
params = {'id': xxxx}
endpoint.format(**params)

which is given me a following result,

'/uri/xxxx'

I need to develop a function in PHP which is doing the same thing, and I found a question related this but still I’m not satisfy with that.

What would be the best way to do this kind of a thing with PHP?

Thanks in advance

Community
  • 1
  • 1
Janith Chinthana
  • 3,792
  • 2
  • 27
  • 54
  • 1
    Those answers are pretty much spot on. Either go for the `sprintf` format as suggested, or use [the custom code that works more like you're used to](http://stackoverflow.com/a/17372566/358679). – Wrikken Feb 09 '14 at 05:20
  • @EmilioGort I have a string and parameters as array, I need to replace that string with the parameter values – Janith Chinthana Feb 09 '14 at 05:22
  • @Wrikken any different approach would be welcome – Janith Chinthana Feb 09 '14 at 05:24
  • 1
    @JanithChinthana: different how? More efficient? Can't beat `sprintf`. More like Python? You just _need_ to write the code for that, it does not exist out of the box. So... unless you can tell me _specifically_ how a new method should be different from the ones already offered, there's not much I can dream up for you ;) – Wrikken Feb 09 '14 at 05:27
  • http://us1.php.net/sprintf#example-4874 – Emilio Gort Feb 09 '14 at 05:28
  • actually I tried with `sprintf` but it doesn't help me to replace the key with string, eg : `{id}` – Janith Chinthana Feb 09 '14 at 05:29
  • @JanithChinthana: but the other answers in you linked question _do_. How are they not valid for your use-case? Keep in mind, I won't accept 'I have the feeling that it should be simpler then that' as an answer ;P – Wrikken Feb 09 '14 at 05:35
  • suppose I have more that 5 parameters and I will provide only few, means there are some missing items in the row, so in that case how can I do this with `sprintf` ? – Janith Chinthana Feb 09 '14 at 05:35
  • ok then I will go with http://stackoverflow.com/a/17372566/1219200 thanks all for helps, but ill remain open this question if somebody else may have a different idea – Janith Chinthana Feb 09 '14 at 05:39

1 Answers1

1

Maybe, something like this will satisfy your needs:

function sformat($template, $params) {
    return str_replace(
        array_map(function($v){return '{'.$v.'}';},array_keys($params)),
        $params,
        $template
    );
}

echo sformat('/uri/{action}/{id}', $params = array(
    'id'=>'23',
    'action'=>'open'
));
userlond
  • 3,632
  • 2
  • 36
  • 53