I have this file
1 + 3 = 4 0 + 0 = 0 1 + 2 = 3 1 / 1 = 1 2 * 3 = 6
I want to separate the (firstNum, secondNum, operationUsed(+,-,*,/), and result) into 4 different files
Advertisement
Answer
Don’t know why you would ever need this but here you go
- Use file() to get the file into an array
- Then use explode() to split the string by spaces
- Then push each of the values to the set of values using a loop (foreach)
- Then implode() them and save to file with file_put_contents()
<?php
// read
$array = file('original.txt');
// parse
$set = [
'firstNum' => [],
'secondNum' => [],
'operationUsed' => [],
'result' => [],
];
foreach ($array as $value) {
$value = explode(' ', $value);
$set['firstNum'][] = $value[0];
$set['secondNum'][] = $value[1];
$set['operationUsed'][] = $value[2];
$set['result'][] = $value[3];
}
// write
file_put_contents('firstNum.txt', implode(PHP_EOL, $set['firstNum']));
file_put_contents('secondNum.txt', implode(PHP_EOL, $set['secondNum']));
file_put_contents('operationUsed.txt', implode(PHP_EOL, $set['operationUsed']));
file_put_contents('result.txt', implode(PHP_EOL, $set['result']));