What are some common pitfalls when using preg_replace in PHP for string manipulation?

One common pitfall when using preg_replace in PHP for string manipulation is not properly escaping special characters in the regular expression pattern. To avoid this issue, it's important to use the preg_quote function to escape any special characters in the pattern before using it in preg_replace.

// Incorrect usage without escaping special characters
$string = "Hello, World!";
$pattern = "/Hello,/";
$replacement = "Hi";

$result = preg_replace($pattern, $replacement, $string);
echo $result; // Output: Hi, World!

// Corrected usage with escaping special characters
$string = "Hello, World!";
$pattern = "/".preg_quote("Hello,")."/";
$replacement = "Hi";

$result = preg_replace($pattern, $replacement, $string);
echo $result; // Output: Hi World!