Unable to resolve the array_diff issue
$j[0]='is';
$j[1]='for';
$diff = array_diff($uniqdesc, $j);
foreach($diff as $find){
echo $find."</br>";
$uniquedesc is an array from a string of words. I need to print out all the uncommon words. The above code is working fine and eliminating 'is' 'for'
Now I stored all the common words in a text file. And I need to eliminate those common words from any string of words.
But the code does not seem to work. How to solve this?
开发者_开发知识库 $common = file_get_contents('commonwords.txt');
$commonArray = explode(" ",$common);
sort($commonArray);
$q=0;
array_unique($commonArray);
$jay=array_unique($commonArray);
foreach($jay as $k){
$j[$q]=(string)$k;
$q=$q+1;
}
$q=0;
for($q=0;$q<20;$q++)
{
echo $j[$q];// This is for testing. It printed the first 20 strings correctly.
}
$diff = array_diff($uniqdesc, $j);
foreach($diff as $find){
echo $find."</br>";
It may be an issue with there being whitespace on either side of the text from your file. Furthermore, it may also be an issue that array_diff() distinguishes between word cases.
For example:
$a = array("word");
$b = array("WORD");
$c = array_diff($a, $b);
// $c = array("WORD", "word");
You may need to convert $uniqdesc
to contain only lower or upper case characters.
If you try the following code and it doesn't work either, it's probably a text upper/lower case mismatch that's causing the problems:
$words = file_get_contents("commonwords.txt");
$words = explode(" ", $words);
for ($i = 0, $sz = count($words); $i < $sz; $i++) { $words[$i] = trim($words[$i]); }
$words = array_unique($words);
$diff = array_diff($uniqdesc, $words);
foreach ($diff as $find) { /* Do stuff */ }
精彩评论