What is a common pitfall when using regular expressions in PHP for replacing multiple occurrences of a specific pattern within a string?

A common pitfall when using regular expressions in PHP for replacing multiple occurrences of a specific pattern within a string is not using the correct regex modifier to replace all occurrences. To replace all occurrences, the "g" modifier should be used.

// Incorrect way without the "g" modifier
$string = "apple, orange, banana, apple";
$pattern = "/apple/";
$replacement = "pear";
$result = preg_replace($pattern, $replacement, $string);
echo $result; // Outputs: "pear, orange, banana, pear"

// Correct way with the "g" modifier
$string = "apple, orange, banana, apple";
$pattern = "/apple/";
$replacement = "pear";
$result = preg_replace($pattern, $replacement, $string, -1, $count);
echo $result; // Outputs: "pear, orange, banana, pear"