How to trim line php?

Issue

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?

Solution

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 🙂

Answered By – Rajpal Singh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published