如何使用 php 更新 ini 文件?
我有一个已创建的现有 ini 文件,我想知道是否有办法更新该文件的一部分,还是每次都必须重写整个文件?
以下是我的 config.ini 文件的示例:
[config]
title='test'
status=0
[positions]
top=true
sidebar=true
content=true
footer=false
假设我想更改 [positions] top=false
。那么我是否会使用 parse_ini_file 来获取所有信息,然后进行更改并使用 fwrite 重写整个文件。或者有没有办法改变该部分?
I have an existing ini file that I have created and I would like to know if there was a way to update a section of the file or do I have have to rewrite the entire file each time?
Here is an example of my config.ini file:
[config]
title='test'
status=0
[positions]
top=true
sidebar=true
content=true
footer=false
Say I want to change the [positions] top=false
. So would I use the parse_ini_file to get all of the infromation then make my changes and use fwrite to rewrite the whole file. Or is there a way just to change that section?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我使用了你的第一个建议:
I used the first suggestion of you:
如果使用 PHP INI 函数,则每次都必须重写该文件。
如果您编写自己的处理器,则可以(有限制)就地更新。如果插入的内容比删除的内容长或短,则无论如何您都必须重写文件。
If you use the PHP INI functions, you must rewrite the file each time.
If you write your own processor, you could (with limitations) update in place. If your insertions are longer or shorter than your deletions, you'll have to rewrite the file anyhow.
这是一个完美的示例,说明您可以使用正则表达式来替换文本字符串。查看 preg_replace 函数。如果您不太确定如何使用正则表达式,您可以在此处找到一个很棒的
教程澄清你需要做这样的事情:
其中 $pattern 是你要匹配的正则表达式, $replacement 是你的替换值。
This is a perfect example of when you could use regular expressions to replace a string of text. Check out the preg_replace function. If you're not quite sure how to use regular expressions you can find a great tutorial here
Just to clarify you'll need to do something like this:
Where $pattern is your regex to match and $replacement is your replacement value.