使用strpos()时遇到问题


Having trouble using strpos()

这个函数会产生6个匹配,尽管它应该会产生2个匹配。我不确定我在这里做错了什么。

public function displayPrize() {
        $testString = "The cow jumped over the moon";
        $userString = "The cow";
        $magicArray = (explode(" ", $testString));
        foreach ($magicArray as $value) {
            if (strpos(" ", $userString, $value) !== false) {
                $count++;
            }
        }
        echo $count . ' matches';
    }
if (strpos(" ", $userString, $value) !== false)

必须成为

if (strpos($userString, $value) !== false)

使用array_entersect()的替代方法:

$testString = 'The cow jumped over the moon';
$userString = 'The cow';
$testStringArray = explode(' ', $testString);
$userStringArray = explode(' ', $userString);
$result = count( array_intersect($testStringArray, $userStringArray) ); // 2