Home > database >  How to trim line php?
How to trim line php?

Time:06-12

I have the following function to split each line from file and group it by columns count:

public function splitfile(Request $request)
{
    $groups = [];
    $session = Session::where('id', $request->id)->first();
    $file = Storage::get($session->filepath);

    $separator = "\r\n";
    $line = strtok($file, $separator);

    while ($line) {
        $line = strtok($separator);
        $splitted = explode("|", $line);
        $cols = count($splitted);
        $groups[$cols][] = $line;
    }

    return response()->json($groups);
}

As result I got array of arrays:

[24: [line1, line2...], 1: [false]]

Problem is here: 1: [false]. Probably it is empty line. How to trim it?

CodePudding user response:

Try the updated code will skip the lines which are empty.

public function splitfile(Request $request){
    $groups = [];
    $session = Session::where('id', $request->id)->first();
    $file = Storage::get($session->filepath);

    $separator = "\r\n";
    $line = strtok($file, $separator);

    while ($line) {
        $line = strtok($separator);
        if($line){
            $splitted = explode("|", $line);
            $cols = count($splitted);
            $groups[$cols][] = $line;
        }
    }
    return response()->json($groups);
}

May it helps :)

  •  Tags:  
  • php
  • Related