this is my code
JavaScript
x
<?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
JavaScript
hahah
i want like this
JavaScript
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…
JavaScript
$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 );