String parse for PHP array

Asked

Viewed 240 times

0

I have the following string:

/dev/sda1      ext4      19620732  16936800   1664184
udev           devtmpfs     10240     10240         0
tmpfs          tmpfs       101232     96740      4492
tmpfs          tmpfs       253080    253080         0
tmpfs          tmpfs         5120      5120         0
tmpfs          tmpfs       253080    253080         0
var 89www        vboxsf   487350400 350068644 137281756

I want to pass the string in question to array, so that the final structure is:

Array
(
    [0] => Array
        (
            [sistArq] => /dev/sda1
            [tipo] => ext4
            [tamanho] => 19620732
            [disponivel] => 16936800
            [usado] => 1664184
        )

    [1] => Array
        (
            [sistArq] => udev
            [tipo] => devtmpfs
            [tamanho] => 10240
            [disponivel] => 10240
            [usado] => 0
        )

    [2] => Array
        (
            [sistArq] => tmpfs
            [tipo] => tmpfs
            [tamanho] => 101232
            [disponivel] => 96740
            [usado] => 4492
        )

    [3] => Array
        (
            [sistArq] => tmpfs
            [tipo] => tmpfs
            [tamanho] => 253080
            [disponivel] => 253080
            [usado] => 0
        )

    [4] => Array
        (
            [sistArq] => tmpfs
            [tipo] => tmpfs
            [tamanho] => 5120
            [disponivel] => 5120
            [usado] => 0
        )

    [5] => Array
        (
            [sistArq] => tmpfs
            [tipo] => tmpfs
            [tamanho] => 253080
            [disponivel] => 253080
            [usado] => 0
        )

    [6] => Array
        (
            [sistArq] => var 89www
            [tipo] => vboxsf
            [tamanho] => vboxsf
            [disponivel] => 487350400
            [usado] => 350068644
        )

)

I tried something like:

$output = trim(preg_replace('/^.+\n/', '', $string));
$output = explode("\n", $output);
$output = preg_replace('/[ ]{1,}/', ' == ' ,$output);

for ($i = 0; $i < sizeof($output); $i++)
{
    $campos = explode(" == ", $output[$i]);

    $arr[$i] = array(
                'sistArq' => $campos[0],
                'tipo' => $campos[1],
                'tamanho' => $campos[2],
                'disponivel' => $campos[3],
                'usado' => $campos[4]
                );
}

However, I did not have the expected success.

  • In this case it seems easier to use substring than Regex. Incidentally, the columns may not be fixed depending on the size of the information listed, but it would be the case to take a look at the command flags to see which ones affect the output formatting (for example, force Posix format, these things)

  • the columns are separated by a tab? if it is he only read each row with a explode n or r and in each row you give a explode to the tab

  • detail the generation of that file in your question?

  • 1

    This output comes from the Linux terminal, the columns are separated by space. Since the first column has several spaces as separator, the others can have only 1 space or several sequentially

2 answers

1


Should work:

$string = "/dev/sda1      ext4      19620732  16936800   1664184\n" .
          "udev           devtmpfs     10240     10240         0\n" .
          "tmpfs          tmpfs       101232     96740      4492\n" .
          "tmpfs          tmpfs       253080    253080         0\n" .
          "tmpfs          tmpfs         5120      5120         0\n" .
          "tmpfs          tmpfs       253080    253080         0\n" .
          "var 89www        vboxsf   487350400 350068644 137281756";

$arr = [];

foreach(preg_split("/((\r?\n)|(\r\n?))/", $string) as $line){
    preg_match("/^([\/\w\d ]+) +([\w\d]+) +(\d+) +(\d+) +(\d+)$/", $line, $campos);

    $arr[] = [
        'sistArq' => trim($campos[1]),
        'tipo' => $campos[2],
        'tamanho' => $campos[3],
        'disponivel' => $campos[4],
        'usado' => $campos[5]
        ];
}

var_dump($arr);
  • one of the items is not loaded, are 7 and due to the line that has / he ignores!!!. has to have an adjustment!

  • 1

    Thank you, I made the modification.

0

I made the logic backwards by taking the array of back to front and when column limit was equal to 4, everything else is key sistArq. In this function pass the directory and file name with extension.

Functional Example

Function searching for a text type variable:

$txt = "/dev/sda1      ext4      19620732  16936800   1664184
        udev           devtmpfs     10240     10240         0
        tmpfs          tmpfs       101232     96740      4492
        tmpfs          tmpfs       253080    253080         0
        tmpfs          tmpfs         5120      5120         0
        tmpfs          tmpfs       253080    253080         0
        var 89www adadfaas       vboxsf   487350400 350068644 137281756";

function parse_file_terminal_linux_string($txt)
{
    $ponteiro = explode("\n", $txt);
    foreach ($ponteiro as $key => $value) 
    {
        $values = explode(" ", $value);     
        $keys = array('usado','disponivel','tamanho','tipo','sistArq'); 
        for($i = count($values); $i >=0 ; $i--)
        {
            if (!empty($values[$i]))
            {
                if (count($keys)>0) 
                    $c = array_shift($keys);                        
                $result[$key][$c] = ($c === 'sistArq' && isset($result[$key][$c])) 
                    ? $result[$key][$c]." ".trim($values[$i])
                    : trim($values[$i]);
            }
        }
        $result[$key]['sistArq'] =
            implode(" ", array_reverse(explode(" ",$result[$key]['sistArq'])));
    }   
    return $result; 
}

Function searching for a text file:

function parse_file_terminal_linux($name = "arq.txt")
{
    $ponteiro = file($name);
    foreach ($ponteiro as $key => $value) 
    {
        $values = explode(" ", $value);     
        $keys = array('usado','disponivel','tamanho','tipo','sistArq'); 
        for($i = count($values); $i >=0 ; $i--)
        {
            if (!empty($values[$i]))
            {
                if (count($keys)>0) 
                    $c = array_shift($keys);                        
                $result[$key][$c] = ($c === 'sistArq' && isset($result[$key][$c])) 
                    ? $result[$key][$c]." ".trim($values[$i])
                    : trim($values[$i]);
            }
        }
        $result[$key]['sistArq'] =
            implode(" ", array_reverse(explode(" ",$result[$key]['sistArq'])));
    }   
    return $result; 
}

print_r(parse_file_terminal_linux("files/arq.txt"));
  • From what I understand of the code you are reading the array, however, I want to transform the string into an array. With the exception of the first column, all the others have no space between their characters, so I need to create some logic that allows me to take the values of the columns and generate an array, and the common delimiter will be the space. Total columns will always be 4

  • @Fabio, I made the editing function are equal, what changed is that one reads a text with line break ("\n") and the other a file also with line break. I hope I helped! The number of columns is 5 and the last can have spaces, first of all test the examples of the two answers and use for you the best.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.