Replacing a single variable
If you have a single variable to replace, you can use this simple regex:
$text = preg_replace('/#fruit\b/', $fruit, $string);
The \b after #fruit ensures that we don't accidentally replace #fruit2 for example.
Replacing multiple variables
If you have multiple variables to replace, you can replace them all at once with preg_replace_callback:
$vars = array(
'fruit' => 'apple',
'color' => 'red',
);
$text = preg_replace_callback('/#(\w+)\b/', function($match) use ($vars) {
if (isset($vars[$match[1]])) {
return $vars[$match[1]];
} else {
return $match[0];
}
}, $string);
The regex will match any # followed by letters and numbers and _ (the \w matches [a-zA-Z0-9_]). For each match, if a variable with that name exists in $vars, it gets replaced by the variable value.
If you want to replace the variables with true PHP variables (e.g. replace #fruit with the value of $fruit), set $vars to $GLOBALS:
$vars = $GLOBALS;
But don't do that. If the string comes from users, they will be able to get the value of any of your variables.
Replacing multiple variables with PHP < 5.3
The previous solution uses a closure, so you need PHP 5.3 to execute it.
If you don't have PHP5.3 you can do the same with this:
class Replacer {
private $vars = array(
'fruit' => 'apple',
'color' => 'red',
);
function replace($match) {
if (isset($this->vars[$match[1]])) {
return $this->vars[$match[1]];
} else {
return $match[0];
}
}
}
$text = preg_replace_callback('/#(\w+)\b/', array(new Replacer, 'replace'), $string);
Why using a class for this ? This way the function can access $this->vars, this avoids using a global variable.
Variable interpolation
If you are trying to insert variables inside of string literals, PHP can do it for you:
$fruit = 'apple';
$string = "The fruit is: $fruit";
When you use double quotes to enclose your strings, PHP recognizes variables and replace them automatically.
$strin="This is %s", and use sprintf instead. But I don't know which way is faster.