Search code examples
phparraysfilepreg-splitfile-read

get string from text file and divide into array


I wants to divide the string from text file.

if the .txt file has been read from some location. i wants to read the file and get strings in array.

Text file have following data

aaa  1111111,
    2hajakka,
    87uj5687,
     F2tryty   
bbb  45454545,
    rereer,
    87uj5687,
     4343343,
    944dsdds

I wants to store lines in array like

$arr = array(
"aaa 1111111, 2hajakka, 87uj5687, F2tryty ",
"bbb 45454545, rereer, 87uj5687, 4343343, 944dsdds");

notes:
data have starts first line as name, like(aaa,bbb) data's separated by commas. if comma not in the line it goes to next array field

Thanks in advance


Solution

  • $file_handle = fopen("myfile.txt", "r");
    $arr[] = "";
    $i = 0;
    $temp_string = '';
    
    while (!feof($file_handle)) {
    $line = fgets($file_handle);
    if(strpos($line,",")!== false)
    {
    $temp_string = $temp_string.$line;}
    else{
    $temp_string = $temp_string.$line;  
    $arr[$i] = $temp_string;
    $temp_string = '';
    $i++;}
    }