如何替换无法完全加载到内存中的文件中的字符串
我可以一次读取几个字节,但我如何确定我没有读到我的短语中间?
我想我应该保存最后strlen(phrase)
的字节长度并尝试替换 last+current
这是我的 WIP
function stream_str_replace(string $search, string $replace, $handle, int $length, &$count = null)
{
// assure $handle is a resource
if (!is_resource($handle)) {
throw new UnexpectedValueException('handle must be a valid stream resource');
}
// assure $handle is a stream resource
if ($resourceType = get_resource_type($handle) !== 'stream') {
throw new UnexpectedValueException('handle must be a valid stream resource, but is a "' . $resourceType . '"');
}
$sLength = strlen($search);
$lastInSLength = '';
while (!feof($handle)) {
$str = fread($handle, $length - $sLength - 1);
$batchCount = 0;
$res = str_replace($search, $replace, $lastInSLength . $str, $batchCount);
if ($batchCount) {
$count += $batchCount;
fseek($handle, -($length - 1));
fwrite($handle, $res); // this does not seem to work as I intend it to
}
$lastInSLength = substr($str, -$sLength);
}
}
$fh = fopen('sample.txt', 'r+');
stream_str_replace('consectetur', 'foo', $fh, 50, $count);
fclose($fh);