Home >Backend Development >PHP Tutorial >PHP处置文件内容

PHP处置文件内容

WBOY
WBOYOriginal
2016-06-13 12:09:10805browse

PHP处理文件内容
我要的效果很简单,就是打开一个文件(格式自定),把这个文件的第N行的一张图片链接(以http://p7.game.com/pic.png为例)替换成相对路径(../images/pic.png),不可以把内容写入到新的文件里面,
------解决思路----------------------

$fn = 'filename';<br />$fp = fopen($fn, 'r+');<br />$size = filesize($fn);<br />$offs = 0;<br />$n = 0;<br />while($buf = fgets($fp)) {<br />  $n++;<br />  if($n == N) break;<br />  $offs = ftell($fp);<br />}<br />$thru = fread(fp, $size);<br />$buf = '..' . substr($buf, 6);<br />fseek($fp, $offs);<br />fwrite($fp, "$buf\n$tfrh");<br />ftruncate($fp);<br />fclose($fp);<br /><br />

------解决思路----------------------
test.txt
<br />11111111<br />2222222<br />33333333<br />44444444<br />55555555<br />66666666<br />77777http://p7.game.com/pic.png777<br />888888888<br />99999999999<br />


<br />$line = 7;<br />$search = 'http://p7.game.com/pic.png';<br />$replace = '../images/pic.png';<br /><br />$content = file_get_contents('test.txt');<br />$data = explode(chr(10), $content);<br /><br />if(isset($data[$line-1])){<br />    $data[$line-1] = str_replace($search, $replace, $data[$line-1]);<br />    file_put_contents('test.txt', implode(chr(10), $data));<br />}<br />

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn