Answer the question
In order to leave comments, you need to log in
How to remove partial line repeats in php?
Good day.
There are files with lines like:
album-58860049 _210149013
album-58860049 _210149014
album-58860049 _210149015
album-13123339_210143131
As you can see, the first 3 lines have a non-unique album indicator (its length can be different.)
How to leave only 1 option?
To get a list after processing, let's say this:
album-58860049 _210149015
album-13123339_210143131
Answer the question
In order to leave comments, you need to log in
A banal option:
- open a file for reading,
- create a new file for writing,
- create an empty array.
- for each line read:
- select an album from it,
- if such an entry is not yet in the array:
---- add it to the array,
---- write the line to the output file.
If the output file is not needed, instead we work with an array in memory, the logic is the same.
Thank you all, here's the script, that's who will come in handy.
<?php
$input = file('album.txt');
$data = array();
foreach ($input as $value) {
$str = substr($value, 0, strpos($value, '_'));
if (in_array($str, $data)) {
} else {
$data[] = $value;
echo $value."
";
}
$data[] = $str;
}
?>
$albums = explode("\r\n", file_get_contents( 'file.txt') );
$result = [];
foreach($albums as $item){
$frag = explode('_', $item, 2);
$result[ $frag[0] ] = $frag[1];
}
$newstr = "";
foreach($result as $key => $val ){
$newstr .= $key .'_'. $val . "\r\n";
}
file_put_contents( 'newfile.txt', $newstr);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question