Replacing a string in a file with another string.

I have wrote a function to replace an user password in passwd file under linux as follows:

function replace_passwd_full($filename,$username,$newpasswd)
{
$separator = ":";
$data=file($filename);
if (!($pipe = fopen($filename, "w"))) {
return false;
}
$size=count($data);
for($line=0;$line<$size;$line++) {
$dataline = $data[$line];
$dataline= preg_replace("/".$username.":(\S+):/i", $username.":".$newpasswd.":\$3", $dataline);
fputs($pipe,$dataline);
}
fclose($pipe);
return true;
}

Hope that helps!! :roll: :wink:
 
Back
Top