Reputation: 2583
Using PHP and/or Codeigniter, I want to create some string templates to be store in a database so that later, they can be used to print out a customize statement.
For example, I want to store this "hello %s! you are the %d visitor."
in my database so that later I can plug in a name and number to print out this message "hello bob! you are the 100 visitor"
.
Are there any available functions to easily do this or will I have to write my own script using preg_match/preg_replace?
This works:
<?
$test = 'hello %s';
$name = 'bob';
printf( $test, $name );
?>
Read more: http://php.net/manual/en/function.printf.php
Upvotes: 2
Views: 1117
Reputation: 1
If you are using CI, you are probably better off storing the strings in a language file.
http://codeigniter.com/user_guide/libraries/language.html
Upvotes: 0
Reputation: 41837
you can use sprintf
, but you'd always need to know the exact order in which to feed the template its arguments. I'd suggest something more along the lines of
// this works only on php 5.3 and up
function sformat($template, array $params)
{
return str_replace(
array_map(
function($key)
{
return '{'.$key.'}';
}, array_keys($params)),
array_values($params), $template);
}
// or in the case of a php version < 5.3
function sformat($template, array $params)
{
$output = $template;
foreach($params as $key => $value)
{
$output = str_replace('{'.$key.'}', $value, $output);
}
return $output;
}
echo sformat('Hello, {what}!', array('what' => 'World'));
// outputs: "Hello, World!"
Upvotes: 4