1

I want to know what is the best approach to edit a specific block of text in a text file ?

For example if the text file contains the following blocks:

[account]
disabled                      = 1
user                          = user1
pwd                           = 1234
id                            = 1
group                         = 11

[account]
disabled                      = 0
user                          = user2
pwd                           = 1234
id                            = 2
group                         = 21

We have two blocks of data , how can i reach for the example block that belongs to a specific user (usernames are unique) and change some values like user,disabled ...etc

if all the data can be placed in one line this would be much easier with the following function:

        $Read = file($fileDir);
        foreach ($Read as $LineNum => $line) {
            $LineParts = explode(' ', $line);
            if ($LineParts[0] == $username) {
            //code goes here 
        }}

Is there something similar ,but at block level (multiple consecutive lines) ?

Note: a lot of you will suggest database, but this file will be read from specific process on the system , so this work is done along with the database.

Regards

jmvcollaborator
  • 2,141
  • 1
  • 6
  • 17
Colin Jack
  • 209
  • 3
  • 13
  • 1
    This is a difficult task to do. I myself tried to do the same thing but could never build error-proof solution for it. I think your best bet is to use already existing solutions like YAML. It uses the same structure and you can get any value from the file by looking for the key e.g. [account][user1]. Without Yaml you may need to atleast use JSON to make it work. Anyway good luck – samayo Oct 08 '22 at 23:50
  • 4
    That looks like an INI file. You could use the solution here to read and write to an INI file: https://stackoverflow.com/questions/5695145/how-to-read-and-write-to-an-ini-file-with-php – Nick ODell Oct 09 '22 at 00:11
  • 2
    Without a defined grammar for the file this is not possible. With a defined grammar it is really easy. With Yaml or JSON there well defined grammars - and off the shelf tools if you are not capable of writing one yourself. But that's not much help if you already have a huge dataset in this format (although if you do have a large database stored in tect iles like this, then you have a whole lot of other problems to deal with too. – symcbean Oct 09 '22 at 00:39
  • 1
    This is what "compiler compilers" are for. Using a formal grammar you can implement a generic parser without having to actually code it. Tools like `bison` or `yacc` come into mind. There actually is a php port here: https://github.com/ircmaxell/PHP-Yacc/ Take a look at the examples in there. – arkascha Oct 09 '22 at 05:13

0 Answers0