0

I get values from the textarea as follows:

2342
de20343
23094
zz900
234432
zz900
2342

I want to find duplicates (eg: "zz900" and "2342") and delete them. In addition, blank lines must be removed.

Is there a single function that will do this?

eebbesen
  • 5,070
  • 8
  • 48
  • 70
od_
  • 183
  • 3
  • 16

3 Answers3

2

Have you tried exploding the text by a newline, and use array_unique to remove duplicates and use array_filter to remove empty lines?

Something like:

<?php
$text = '2342
de20343
23094
zz900
234432
zz900
2342';

$array = explode (PHP_EOL, $text);
$unique = array_filter (array_unique ($array));

echo join (PHP_EOL, $unique);
?>
  • You don't reindex your array, so the indexes could be: `2,4,5,13` – Rizier123 Feb 26 '15 at 13:44
  • I guessed he just wanted to remove the duplicates and send or store it as a text field, not use it as an array; in this way reindexing is not necessary.. – Micha van Eijk Feb 26 '15 at 14:00
  • This solution is the shortest and works good, but when i paste the result in the textarea the cursor is at the top of the list, not at the bottom. So if i use a barcode reader to add a new line it will concatenate with the first line. how to avoid that ? – cetipabo Oct 08 '20 at 12:07
1

This should work for you:

$parts = array_values(array_unique(array_filter(explode(PHP_EOL, $str))));
print_r($parts);

As an example:

$str = "
2342
de20343
23094


zz900
234432
zz900
2342";

$parts = array_values(array_unique(array_filter(explode(PHP_EOL, $str))));
print_r($parts);

Output:

Array ( [0] => 2342 [1] => de20343 [2] => 23094 [3] => zz900 [4] => 234432 )
Rizier123
  • 58,877
  • 16
  • 101
  • 156
0
Check this, this is new code:-

<?php
$string_old = "2342
de20343

_
_
23094
zz900
234432
zz900
2342";
$array_by_exploding_through_next_line = explode ("\n",$string_old);
$new_array = array();
foreach($array_by_exploding_through_next_line as $key => $value){
    if(strpos($array_by_exploding_through_next_line[$key], '_') !== FALSE || strpos($array_by_exploding_through_next_line[$key], ' ') !== FALSE){
    }else{
        $new_array[] = $value;
    }
}
$string_new = implode('',array_unique($array_by_exploding_through_next_line));
print_r($array_by_exploding_through_next_line);
echo "<br>";
echo $string_new;
die;
?>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98