How can I replace a variable in a string with the value in PHP?
When retrieving content from a database, you often encounter strings where placeholders remain unchanged because they are stored as literal text rather than evaluated variables. In your specific case, the database holds the string I am a {$club} fan. You have defined $club = "Barcelona" in your application code, but simply echoing the raw database value results in I am a {$club} fan instead of the expected I am a Barcelona fan. This happens because PHP does not automatically evaluate variables inside curly braces when they appear within a double-quoted string that was originally defined as a static string literal.
To resolve this, you need to explicitly perform a string replacement or use a method that evaluates the expression. The most direct approach using standard PHP functions is str_replace. However, because your placeholder uses curly braces {}, a simple replacement might be fragile if the actual data contains similar patterns elsewhere. A more robust solution for this specific pattern involves parsing the string to identify and replace only the intended variables.
You can achieve the desired output by extracting the variable name from the placeholder and replacing it with the corresponding value. Here is a practical implementation using preg_replace:
$club = "Barcelona";
$data_base[0]['body'] = 'I am a {$club} fan';
// Extract the variable name from inside the curly braces
$pattern = '/\{\$(.*?)\}/';
$replacement = '$1'; // This creates a placeholder for back-referencing if needed, but we want to replace with $club value
// A simpler approach for known variable names in this specific format:
$result = preg_replace('/\{\$([a-zA-Z_][a-zA-Z0-9_]*)\}/', '[$1]', $data_base[0]['body']);
// Now inject the actual value. This requires a two-step logic or direct replacement:
$finalString = str_replace('{$club}', $club, preg_replace('/\{[^}]+\}/', '', $data_base[0]['body']));
Wait, that last example is getting messy because str_replace replaces text, not variables. The cleanest way to handle this without writing a complex parser from scratch is to treat the string as a template and use preg_replace with an anonymous function or simply replace the literal placeholder text if you control the database format.
If you can modify how the data is stored, consider storing the value directly:
$data_base[0]['body'] = str_replace('{$club}', $club, $data_base[0]['body']);
echo $data_base[0]['body']; // Outputs: I am a Barcelona fan
However, if you must handle this at runtime without altering the database schema immediately, preg_replace with a callback allows you to dynamically resolve variables that exist in the current scope. Note that this only works if the variable name inside the braces matches a variable currently defined in your PHP script (e.g., $club).
$data_base[0]['body'] = 'I am a {$club} fan';
$club = "Barcelona";
$processed = preg_replace_callback(
'/\{\$(.*?)\}/',
function ($matches) use ($club) {
$varName = $matches[1];
// Check if the variable exists and is not empty
if (isset($$varName) && $$varName !== '') {
return $$varName;
}
return $matches[0]; // Return original if variable doesn't exist or is empty
},
$data_base[0]['body']
);
echo $processed;
This approach dynamically looks up the variable $club and replaces {$club} with its value. It handles cases where multiple variables might be present in the future, provided they are defined before the replacement occurs.
Performance and Security Considerations
While this dynamic evaluation is convenient, it introduces security risks if the input comes from an untrusted source. Using $$varName (variable variable) allows the string to potentially reference arbitrary global variables. If an attacker can inject a placeholder like {$GLOBALS['malicious_var']}, they could access sensitive data stored in global scope. Always validate that the variable name inside the braces is part of a known, safe list or use strict allowlisting before performing dynamic evaluation.
Additionally, be aware that this technique does not support expressions (like {$user_age + 5}) unless you implement a full expression parser. For simple placeholder replacement where the variable names are fixed and defined in your application context, this method provides a balance between ease of implementation and safety, provided you sanitize the input and validate the variable names against a whitelist.