What considerations should be made regarding text file encoding when performing text replacements in PHP?

When performing text replacements in PHP, it is important to consider the encoding of the text file being manipulated. If the file is not in the expected encoding, it can lead to issues with special characters or unexpected behavior. To ensure proper handling of text encoding, it is recommended to specify the encoding when reading and writing files in PHP.

// Specify the encoding when reading the file
$fileContent = file_get_contents('example.txt', FILE_TEXT | FILE_IGNORE_NEW_LINES, null, 'UTF-8');

// Perform text replacement
$newContent = str_replace('old text', 'new text', $fileContent);

// Specify the encoding when writing the file
file_put_contents('example.txt', $newContent, FILE_TEXT | FILE_IGNORE_NEW_LINES, null, 'UTF-8');