What are the potential pitfalls of using preg_replace in PHP to replace specific words in a text file?
Using preg_replace in PHP to replace specific words in a text file can lead to unintended replacements if the pattern used is not carefully crafted. To avoid this, it's important to use word boundaries (\b) in the regex pattern to ensure that only whole words are matched and replaced. This will prevent partial matches or replacements within larger words.
$file_contents = file_get_contents('textfile.txt');
$replaced_contents = preg_replace('/\bword\b/', 'replacement', $file_contents);
file_put_contents('textfile.txt', $replaced_contents);