What are some best practices for reading and modifying text files in PHP, especially when it comes to searching for specific options and values?

When reading and modifying text files in PHP, it's important to handle the file operations properly to avoid data corruption or loss. One best practice is to use file locking to prevent simultaneous modifications by multiple processes. Additionally, when searching for specific options and values within a text file, it's recommended to use regular expressions or string manipulation functions to efficiently locate and modify the desired content.

<?php
// Read the contents of the text file
$file = 'example.txt';
$contents = file_get_contents($file);

// Search for a specific option and value
$searchOption = 'option1';
$searchValue = 'value1';
$pattern = "/$searchOption:.*?$/m";
if (preg_match($pattern, $contents, $matches)) {
    // Modify the value if found
    $newValue = 'new_value';
    $newContents = preg_replace("/$searchOption:.*?$/m", "$searchOption: $newValue", $contents);

    // Write the modified contents back to the file
    file_put_contents($file, $newContents);
}
?>