Skip to content
Advertisement

php remove duplicate except original

this is my code

   <?php 

    $string = 'this
    this 
    good 
    good 
    hahah';

    $rows = explode("n",$string);
    $unwanted = 'this|good';
    $cleanArray= preg_grep("/$unwanted/i",$rows,PREG_GREP_INVERT);
    $cleanString=implode("n",$cleanArray);
    print_r ( $cleanString );

?>

display

hahah

i want like this

this 
good 
hahah

i want to keep one… please help me, thanks guys

Advertisement

Answer

This code resorts to checking each line to see if it matches your $unwanted string, but it also creates an array of strings it has already encountered so it checks if it has previously been encountered ( using in_array()). If it matches and has been encountered before it uses unset() in the original $rows to remove the line…

$string = 'this
    this
    good
   good
    hahah';

$rows = explode("n",$string);
$unwanted = 'this|good';
$matched = [];
foreach ( $rows as $line => $row )   {
    if ( preg_match("/$unwanted/i",$row, $matches))  {
        if ( in_array(trim($matches[0]), $matched) === true )    {
            unset($rows[$line]);
        }
        $matched[] = $matches[0];
    }
}
$cleanString=implode("n",$rows);
print_r ( $cleanString );
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement