What are the potential pitfalls of using str_replace() in PHP for replacing placeholders in text retrieved from a database?
Potential pitfalls of using str_replace() for replacing placeholders in text retrieved from a database include the lack of flexibility in handling different placeholders, the possibility of accidentally replacing unintended text, and the potential for inconsistent results if the placeholders are not unique. To solve this issue, it is recommended to use a more robust solution such as using regular expressions with preg_replace() to ensure accurate and reliable placeholder replacement.
// Example code snippet using preg_replace() for placeholder replacement
$placeholders = array(
'{name}' => 'John Doe',
'{age}' => '30'
);
$text = "Hello {name}, you are {age} years old.";
foreach($placeholders as $placeholder => $value) {
$text = preg_replace('/' . preg_quote($placeholder, '/') . '/', $value, $text);
}
echo $text;