views:

61

answers:

3

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

+3  A: 

you can use any of *printf() functions family

Col. Shrapnel
+3  A: 

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!"
Kris
Thanks, you solved the problem that I was really thinking of but forgot by the time I asked the question.
wag2639
you're welcome. many of us have had this problem many times before ;)
Kris
the thing you say about needing to know the exact order of the arguments for sprintf is false. At the link you posted, check out examples 3 and 4. There is syntax to specify which argument to use, which makes it very useful for the OP's purpose.
rmeador
@rmeador, being able to specify a numeric argument index != as being able to pass in the arguments in any order. you still have to know the order in which the arguments will arrive.
Kris
@rmeador, technically, for the question I asked, sprintf is sufficient, but this way, I get to use system/application variables at will. I can just pass $this into function and it'll work.
wag2639
A: 

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

Are they dynamic though, in that I can customize different text for different users. Basically, I'm making a wall like notice that would say different things to different users, but its going to be administered by a non-programmer.
wag2639
No, they are not dynamic.
Industrial