如果字符串与当前字符串类似,我不想回显字符串。让我们说我们的字符串是,
$strings = array("software","software","game","antivirus");
我的差异功能,
function ($val1,$val2) {
similar_text($val1,$val2,$percent);
if ($percent>83) {
// should not echo. But don't know how to do.
}
}
但我不知道怎么办呢。我猜应该是为每个人使用。
答案 0 :(得分:2)
尝试这样的事情:
$strings = array("software","software","game","antivirus");
$lastString = '';
foreach ($strings as $string) {
similar_text($lastString, $string, $percent);
if ($percent < 83) {
echo "$string<br />";
$lastString = $string;
}
}
如果您不理解其中的某些部分,请发表评论,我会澄清。
修改强>
我把$lastString = $string;
移到了条件中。
考虑以下字符串列表:
$strings = array("software","sofware","sofwart","ofwart","fwart","wart","warts");
将$lastString
作业留在循环之外只会打印software
,即使很多单词非常不同software
它们与前一个单词没那么不同。
将其移到内部实际上会产生输出:
软件
sofwart
疣
答案 1 :(得分:1)
$strings = array("software","software","game","antivirus");
$previous = '';
foreach ($strings as $string) {
if ($string===$previous) {
continue;
} else {
echo $string;
$previous = $string;
}
}
但我觉得最好这样做(它应该更快):
$strings = array("software","software","game","antivirus");
$num = count($strings);
for ($i=0;$i<$num;$i++) {
if ($strings[$i]===$strings[$i-1] && $i!==0) {
continue;
} else {
echo $strings[$i];
}
}
顺便说一下,我完全没有得到$百分比的含义..
答案 2 :(得分:1)
使用array_filter()
的方法(假设> = 5.3):
$strings = array('software', 'software', 'game', 'antivirus');
$filtered = array_filter($strings, function($curr) {
static $prev;
similar_text($prev, $curr, $percent);
$prev = $curr;
if ($percent < 83) {
return $curr;
}
});
print_r($filtered);
收率:
Array
(
[0] => software
[2] => game
[3] => antivirus
)
希望这会有所帮助。实际上,直到现在我才知道similar_text()
。相当有趣的功能。谢谢:))