What are the advantages of using preg_replace_callback over str_replace for string manipulation in PHP, as discussed in the forum thread?
When dealing with complex string manipulations in PHP, using preg_replace_callback offers more flexibility and power compared to str_replace. preg_replace_callback allows you to use a callback function to process matches found using regular expressions, enabling dynamic replacements or transformations. This can be especially useful when you need to perform more advanced string manipulations that go beyond simple text replacements.
$string = "Hello, my name is [name]. I am [age] years old.";
$replacements = [
'name' => 'John',
'age' => 30
];
$result = preg_replace_callback('/\[(.*?)\]/', function($matches) use ($replacements) {
$key = $matches[1];
return isset($replacements[$key]) ? $replacements[$key] : $matches[0];
}, $string);
echo $result;