What are some common pitfalls when using preg_replace in PHP for variable replacement in a text?

One common pitfall when using preg_replace in PHP for variable replacement in a text is not properly escaping the replacement variables, which can lead to unexpected behavior or errors. To solve this issue, you should use preg_replace_callback instead of preg_replace and pass a callback function that properly escapes the replacement variables.

$text = "Hello, {name}!";
$variables = ['name' => 'John'];

$escapedVariables = array_map('preg_quote', array_keys($variables));
$pattern = '/{(' . implode('|', $escapedVariables) . ')}/';

$result = preg_replace_callback($pattern, function ($match) use ($variables) {
    return $variables[$match[1]] ?? $match[0];
}, $text);

echo $result; // Output: Hello, John!