I am loading a text file into an array:
<?php
$filename = "data.txt";
$array = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>
The file contains certain lines, that start with the word "Data". Those lines are loaded as separate values in the array.
What I wanna do is extract only those values from the array and save those as a separate file, each one on a new line.
How would I go about searching for those specific values in the array and doing the above?
When you have lines of your file in an array, you are stuck with iterating through the array (lines) and checking whether the line starts with Data (0 === mb_strpos($line, 'Data')
). If so, you just save the line to another file with fwrite()
.
Or you could run grep
in console:
grep '^Data' input.txt > output.txt
If you have an array you can filter values with function array_filter. http://php.net/manual/en/function.array-filter.php Function on callback have to return true if you wanna stay element on array, or false if you want to unset it, for example because that element is diffrent then you a looking for. Inside function you have to check is there a words are you looking for or not.
Use preg_match to check value of element and regexes. http://php.net/manual/en/function.preg-match.php
Usefull link for test regexes: https://regex101.com/
Simple!
Example:
<?php
$arrayData = [
'DATA: something',
'DATA: carrot',
'DATA: coffee',
'Mercedes-Benz C32 AMG',
'DATA: hot coffee'
];
function checkArray($value){
$re = '/^DATA:(.*)coffee(.*)/m';
if (preg_match($re, $value)) {
return true;
} else {
return false;
}
}
$filtered = array_filter($arrayData, 'checkArray');
var_dump($fitlered);
The following code will extract all lines starting with "Data" (case sensitive) and append them to the file "data_rows.txt".
$filename = "data.txt";
$array = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach( $array as $item ) {
if( strpos($item, "Data") === 0 ) {
file_put_contents("data_rows.txt", "{$item}
", FILE_APPEND);
}
}