开发者

How can i read a file in php only to a certain character

the fseak function sets a cursor to the file but only an offset, a number.开发者_如何学编程 Is there a function or a way i can set the cursor to a text file after reading a character or a string? Example, lets say i have this text file:

Hi, welcome to your page!

Is there a way i can insert my name for instance, right after the word "Hi" in the text file?


You can read the file into a string, manipulate the string, then re-save the string to the file. If you're running PHP5 you should be able to do this:

$str = file_get_contents('filename.txt');
$str = str_replace('Hi', 'Hi Joe', $str);
file_put_contents($str);


Just put the file contents into a string variable and use PHPs string functions, like strpos(), substr(), etc. When you're done, write back to the file.


you can use substr_replace

I'm inserting my string at index 2 and replacing 0 characters.

//$data = file_get_contents("file.txt");
$data = "Hi, welcome to your page!";
echo substr_replace($data, " Ilia", 2, 0);

this way you don't have to do any string based searches

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜