In the context of PHP, what are the advantages of using preg_replace() over str_replace() for character manipulation tasks?

When it comes to character manipulation tasks in PHP, using preg_replace() offers more flexibility and power compared to str_replace(). preg_replace() allows for the use of regular expressions, which can provide more advanced matching and replacing capabilities. This can be especially useful when dealing with complex patterns or multiple variations of a string that need to be replaced.

// Using preg_replace() to replace a specific pattern in a string
$string = "Hello, my name is John.";
$pattern = '/John/';
$replacement = 'Doe';
$newString = preg_replace($pattern, $replacement, $string);

echo $newString; // Output: Hello, my name is Doe.