PHP Code to Open File and Replace Content
PHP Code Function to Open a File, Replace Content/Text in it, Returning the Altered File
Home
Short:
/* -------------------------------------------------------------- function to open a file [$path] and replace content in it [$oldContent] with [$newContent] and return the altered content --------------------------------------------------------------- */ function fileReplaceContent($path, $oldContent, $newContent) { // Check if the file exists and is readable if(!file_exists($path) || !is_readable($path)) { return [false, "File [" . $path . "] does not exist or is not readable."]; } $content = file_get_contents($path); // Read the content of the file if($content === false) { return [false, "Error opening or reading file at [" . $path . "]"]; } if (!is_writable($path)) // file can't be written to { return [false, "File [" . $path . "] is not writable."]; } // Replace the text $modifiedContent = str_replace($oldContent, $newContent, $content); return [true, $modifiedContent]; }
source code home