Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Better way to convert string with multiple spaces into array

I am reading from files and each line has multiple spaces. Example:

$line = 'Testing Area                               1  10x10';

I need to convert it into array with 3 elements only so I can save it to a table. Final output should be like this:

$final_array = array('Testing Area', '1', '10x10');

This is how I’m doing it so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// read by line
foreach(explode(PHP_EOL, $contents) as $line) {

    // split line by 2 spaces coz distance between `1` and `10x10` is atleast 2 spaces
    $arr = explode('  ', $line);

    // But because `Testing Area` and `1` has so many spaces between them,
    // exploding the $line results to empty elements.
    // So I need to create another array for the final output.

    $final_array = array();

    // loop through $arr to check if value is empty
    // if not empty, push to $final array
    foreach ($arr as $value) {
        if (!empty($value)) {
            array_push($final_array, $value);
        }
    }

    // insert into table the elements of $final_array according to its column
}

Is there a better way to do this instead of looping through the array and checking each element if it’s empty?
Take note that I have multiple files to read, each containing atleast 200 lines like that.

>Solution :

Use preg_split(), with 2 or more spaces as the delimiter.

$array = preg_split('/\s{2,}/', $line);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading