Skip to content
PHP Logo

How can PHP functions like file_exists and str_replace be utilized to manipulate text files effectively?

To manipulate text files effectively using PHP functions like file_exists and str_replace, you can first check if the file exists using file_exists function, then read the content of the file, manipulate the text using str_replace function, and finally write the modified content back to the file.

php
$file_path = 'example.txt';

if(file_exists($file_path)){
    $content = file_get_contents($file_path);
    
    // Manipulate the text
    $new_content = str_replace('old_string', 'new_string', $content);
    
    file_put_contents($file_path, $new_content);
    echo 'Text file has been successfully manipulated.';
} else {
    echo 'File does not exist.';
}