What are the potential pitfalls of using functions like str_replace or preg_replace in PHP for string manipulation tasks?

One potential pitfall of using functions like str_replace or preg_replace in PHP for string manipulation tasks is that they can be inefficient when dealing with large amounts of data or complex patterns. To solve this issue, using the preg_replace_callback function allows for more flexibility and efficiency in handling advanced string replacements.

// Using preg_replace_callback for more efficient string manipulation
$string = "Hello, my name is [name].";
$replacements = [
    'name' => 'John'
];

$new_string = preg_replace_callback('/\[(.*?)\]/', function($match) use ($replacements) {
    return isset($replacements[$match[1]]) ? $replacements[$match[1]] : $match[0];
}, $string);

echo $new_string; // Output: Hello, my name is John.