Skip to content

Instantly share code, notes, and snippets.

@ManishLSN
Created September 11, 2017 13:41
Show Gist options
  • Save ManishLSN/c5b96d506000acdff9f7fd1ae6a9181e to your computer and use it in GitHub Desktop.
Save ManishLSN/c5b96d506000acdff9f7fd1ae6a9181e to your computer and use it in GitHub Desktop.
replace text in a file.
<?php
function replace_in_file($FilePath, $OldText, $NewText)
{
$Result = array('status' => 'error', 'message' => '');
if(file_exists($FilePath)===TRUE)
{
if(is_writeable($FilePath))
{
try
{
$FileContent = file_get_contents($FilePath);
$FileContent = str_replace($OldText, $NewText, $FileContent);
if(file_put_contents($FilePath, $FileContent) > 0)
{
$Result["status"] = 'success';
}
else
{
$Result["message"] = 'Error while writing file';
}
}
catch(Exception $e)
{
$Result["message"] = 'Error : '.$e;
}
}
else
{
$Result["message"] = 'File '.$FilePath.' is not writable !';
}
}
else
{
$Result["message"] = 'File '.$FilePath.' does not exist !';
}
return $Result;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment