What potential pitfalls should be considered when using preg_replace in PHP to modify file contents?

When using preg_replace in PHP to modify file contents, potential pitfalls to consider include accidentally replacing unintended content, not properly sanitizing user input which could lead to security vulnerabilities like code injection, and not handling errors or exceptions that may arise during the replacement process.

// Example code snippet demonstrating how to use preg_replace with proper input validation and error handling

$file = 'example.txt';
$content = file_get_contents($file);

if ($content !== false) {
    $new_content = preg_replace('/pattern/', 'replacement', $content);

    if ($new_content !== null) {
        file_put_contents($file, $new_content);
        echo 'Content replaced successfully.';
    } else {
        echo 'Error replacing content.';
    }
} else {
    echo 'Error reading file content.';
}