How can I replace a variable in a string with the value in PHP?

I have string like this in database (the actual string contains 100s of word and 10s of variable):

I am a {$club} fan

I echo this string like this:

$club = "Barcelona";
echo $data_base[0]['body'];

My output is I am a {$club} fan. I want I am a Barcelona fan. How can I do this?


Use strtr. It will translate parts of a string.

$club = "Barcelona";
echo strtr($data_base[0]['body'], array('{$club}' => $club));

For multiple values (demo):

$data_base[0]['body'] = 'I am a {$club} fan.'; // Tests

$vars = array(
  '{$club}'       => 'Barcelona',
  '{$tag}'        => 'sometext',
  '{$anothertag}' => 'someothertext'
);

echo strtr($data_base[0]['body'], $vars);

Program Output:

I am a Barcelona fan.

/**
 * A function to fill the template with variables, returns filled template.
 *
 * @param string $template A template with variables placeholders {$variable}.
 * @param array $variables A key => value store of variable names and values.
 *
 * @return string
 */

public function replaceVariablesInTemplate($template, array $variables){

 return preg_replace_callback('#{(.*?)}#',
       function($match) use ($variables){
            $match[1] = trim($match[1], '$');
            return $variables[$match[1]];
       },
       ' ' . $template . ' ');
}

I would suggest the sprintf() function.

Instead of storing I am a {$club} fan, use I am a %s fan, so your echo command would go like:

$club = "Barcelona";

echo sprintf($data_base[0]['body'],$club);

Output: I am a Barcelona fan

That would give you the freedom of use that same code with any other variable (and you don't even have to remember the variable name).

So this code is also valid with the same string:

$food = "French fries";

echo sprintf($data_base[0]['body'], $food);

Output: I am a French fries fan

$language = "PHP";

echo sprintf($data_base[0]['body'], $language);

Output: I am a PHP fan


You are looking for nested string interpolation. A theory can be read in the blog post Wanted: PHP core function for dynamically performing double-quoted string variable interpolation.

The major problem is that you don't really know all of the variables available, or there may be too many to list.

Consider the following tested code snippet. I stole the regex from Mohammad Mohsenipur.

$testA = '123';
$testB = '456';
$testC = '789';
$t = '{$testA} adsf {$testB}adf 32{$testC} fddd{$testA}';

echo 'before: ' . $t . "\n";

preg_match_all('~\{\$(.*?)\}~si', $t, $matches);
if ( isset($matches[1])) {
    $r = compact($matches[1]);
    foreach ( $r as $var => $value ) {
        $t = str_replace('{$' . $var . '}', $value, $t);
    }
}

echo 'after: ' . $t . "\n";

Your code may be:

$club = 'Barcelona';
$tmp = $data_base[0]['body'];
preg_match_all('~\{\$(.*?)\}~si', $tmp, $matches);
if ( isset($matches[1])) {
    $r = compact($matches[1]);
    foreach ( $r as $var => $value ) {
        $tmp = str_replace('{$' . $var . '}', $value, $tmp);
    }
}
echo $tmp;

if (preg_match_all('#\$([a-zA-Z0-9]+)#', $q, $matches, PREG_SET_ORDER));
{
    foreach ($matches as $m)
    {
        eval('$q = str_replace(\'' . $m[0] . '\', $' . $m[1] . ', $q);');
    }
}

This matches all $variables and replaces them with the value.

I didn't include the {}'s, but it shouldn't be too hard to add them something like this...

if (preg_match_all('#\{\$([a-zA-Z0-9]+)\}#', $q, $matches, PREG_SET_ORDER));
{
    foreach ($matches as $m)
    {
        eval('$q = str_replace(\'' . $m[0] . '\', $' . $m[1] . ', $q);');
    }
}

Though it seems a bit slower than hard coding each variable. And it introduces a security hole with eval. That is why my regular expression is so limited. To limit the scope of what eval can grab.

I wrote my own regular expression tester with Ajax, so I could see, as I type, if my expression is going to work. I have variables I like to use in my expressions so that I don't need to retype the same bit for each expression.