命名绑定变量在字符串中?

I'm looking for function like sprintf(), except whereas with sprintf() you bind the values by order of arguments, I want something where I can bind variables by name. So, if I had the string "Hello $name! We're please to have you visit, $name!", you could pass an array or something and get the resultant string from it.

Something like the PDO statements, but just for plain strings, not database queries. What can I use?

preg_replace/e or preg_replace_callback is your best bet

  $vars = array('name' => 'Joe', 'age' => 25);
  $str = "@name is @age years old";
  echo preg_replace('/@(\w+)/e', '$vars["$1"]', $str);

Perhaps you could use anonymous functions, such that the free variables are bound as parameters in the anonymous function, which returns a string with the values populating the free variables. This would work well in conjunction with the extract function inside a closure, wherein the keys from your array become real variables within a local scope necessary to evaluate the variables referenced in the format string.

Or there is probably a relatively simple version using eval (this is just an illustration, not tested code):

function named_printf ($format_string, $values) {
    extract($values);
    $result = $format_string;
    eval('$result = "'.$format_string.'";');
    return $result;
}

echo named_printf ('Hello $msg', array('msg'=>'World'));

PHP's scope control mechanisms are a bit scary, so you may want to verify that this isn't going to leak variables into scope all over the place. It'd also be worth santising input.

PHP has built in support for evaluating variables inside of double-quoted strings. While you can't "pass-in" an array to it, you could think of the current variable scope as the input for the string builder "function".

$name = "Kendall Hopkins";
print "Hello {$name}!"; //Hello Kendall Hopkins!

http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

EDIT:

A more flexible solution might be to abstract out the code into a closure. This doesn't depend on eval and will probably run faster.

$hello_two = function ( array $params ) {
    extract( $params );
    return "Hello $name1 and $name2!";
}

//Hello User and Kendall
$hello_two( array( "var1" => "User", "var2" => "Kendall" ) );