Best way to split string data that is limited in php

Seek out php help, best practice. What is a good way to break these lines? I was looking to explode or better regular expression? and then maybe display them in a table? Thanks for your input.

input file:

PRE:abc:KEY1:null:KEY2:/myproject/data/dat_abc_2010120810.gz1
PRE:def:KEY1:sdsu:KEY2:mail_abc.dat.2010120810.gz1

expected output or web page to display:

PRE  KEY1 KEY2
===  ==== ======================================
abc  null /myproject/data/dat_abc_2010120810.gz1
def  sdsu mail_abc.dat.2010120810.gz1
+3
source share
2 answers

If you have such a file, I would do it in two steps, if you were you ...

1st step

Use file () to get an array representing the file.

2nd step

Now you can use explode () to get all the different columns and output them.

Quick example:

<?php
$output = "";

$file = file("data.txt");
foreach ($file as $line)
{
    $cols = explode (":", $line);
    $output .= "{$cols[0]} {$cols[1]}";
}
?>

Hope this helps.

+6

explode :

$fp = fopen('myfile.txt', 'r');
while ($line = fgets($fp))
   $parts = explode(':', $line);
   $array = array();
   for ($i=0; $i<count($parts); $i+=2) {
      $array[$parts[$i]] = isset($parts[$i+1]) ? $parts[$i+1] : 'null';
   }
   print_r($array);
}

:

Array
(
    [PRE] => abc
    [KEY1] => null
    [KEY2] => /myproject/data/dat_abc_2010120810.gz1
)
Array
(
    [PRE] => def
    [KEY1] => sdsu
    [KEY2] => mail_abc.dat.2010120810.gz1
)
+4

Source: https://habr.com/ru/post/1780075/


All Articles