Skip to content

Instantly share code, notes, and snippets.

@Moln
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save Moln/20ec31eda04a85a73b8c to your computer and use it in GitHub Desktop.

Select an option

Save Moln/20ec31eda04a85a73b8c to your computer and use it in GitHub Desktop.
文件内容替换, 锁文件方式
<?php
/**
* 文件行扫描, 按callback 替换
* @param string $file
* @param callable $findCallback
* @param bool $loop
*/
function file_line_replace($file, callable $findCallback, $loop = false)
{
$h = fopen($file, 'cr+');
flock($h, LOCK_EX);
$size = fstat($h)['size'];
$newContents = [];
$find = false;
$cSize = $pos = 0;
while (!feof($h)) {
$content = $tmpContent = fgets($h);
$content = trim($content, "\n");
if ($loop) {
if ($content) {
$find = $findCallback($content) || $find;
$newContents[] = $content;
}
} else {
if (!$find) {
$find = $findCallback($content);
if ($find) {
$newContents[] = $content;
$cSize = strlen(trim($tmpContent, "\n")) - strlen($content);
$pos = ftell($h) - strlen($tmpContent);
}
} else {
$newContents[] = $content;
}
}
}
if ($find) {
$newContents = implode("\n", $newContents) . "\n";
fseek($h, $pos);
fwrite($h, $newContents);
if ($loop) {
ftruncate($h, strlen($newContents));
} else {
ftruncate($h, $size - $cSize);
}
}
flock($h, LOCK_UN);
fclose($h);
}
//"/tmp/tmp.txt" content
/*
abcdef abcdef
abcdef abcdef
abcdef abcdef
*/
//替换后
/*
bbcdef bbcdef
bbcdef bbcdef
bbcdef bbcdef
*/
file_line_replace(
"/tmp/tmp.txt",
function (&$content) {
$content = str_replace('a', 'b', $content);
return true;
},
true
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment