当前位置:Gxlcms > PHP教程 > PHP处置文件内容

PHP处置文件内容

时间:2021-07-01 10:21:17 帮助过:4人阅读

PHP处理文件内容
我要的效果很简单,就是打开一个文件(格式自定),把这个文件的第N行的一张图片链接(以http://p7.game.com/pic.png为例)替换成相对路径(../images/pic.png),不可以把内容写入到新的文件里面,
------解决思路----------------------
$fn = 'filename';
$fp = fopen($fn, 'r+');
$size = filesize($fn);
$offs = 0;
$n = 0;
while($buf = fgets($fp)) {
$n++;
if($n == N) break;
$offs = ftell($fp);
}
$thru = fread(fp, $size);
$buf = '..' . substr($buf, 6);
fseek($fp, $offs);
fwrite($fp, "$buf\n$tfrh");
ftruncate($fp);
fclose($fp);


------解决思路----------------------
test.txt

11111111
2222222
33333333
44444444
55555555
66666666
77777http://p7.game.com/pic.png777
888888888
99999999999



$line = 7;
$search = 'http://p7.game.com/pic.png';
$replace = '../images/pic.png';

$content = file_get_contents('test.txt');
$data = explode(chr(10), $content);

if(isset($data[$line-1])){
$data[$line-1] = str_replace($search, $replace, $data[$line-1]);
file_put_contents('test.txt', implode(chr(10), $data));
}

人气教程排行