PHP equivalent to C# string formatting
I am trying to duplicate my C# string formatting where i can do something like this:
Console.Writeline("My name is [0]. I have been a [1] for [2] days.", "bob", "member", "12")
I want to be able to do this in PHP, but as far as I know the only function that resembles this is sprintf(). Is there a function that is identical to the one above
echo function("My name is [0]. I have been a [1] for [2] days.", "bo开发者_如何学Cb", "member", "12")
You could write your own function like e.g.
<?php
function Format($format /*, ... */) {
$args = func_get_args();
return preg_replace_callback('/\[(\\d)\]/',
function($m) use($args) {
// might want to add more error handling here...
return $args[$m[1]+1];
},
$format
);
}
$x = 'a';
$y = 'b';
echo Format('1=[1], 0=[0]', $x, $y);
You could inline variables in the string:
$frob = "John";
$foo = "Hello $frob!";
精彩评论