Home > Enterprise >  Better way to convert string with multiple spaces into array
Better way to convert string with multiple spaces into array

Time:03-30

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:

// 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.

CodePudding user response:

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

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

CodePudding user response:

Assuming the criteria for splitting be two or more spaces, we can try using preg_split here:

$line = 'Testing Area                               1  10x10';
$final_array = preg_split("/\s{2,}/", $line);
print_r($final_array);

This prints:

Array
(
    [0] => Testing Area
    [1] => 1
    [2] => 10x10
)
  • Related