简体   繁体   中英

Having trouble using strpos()

This function results in 6 matches, although it should result in 2 matches. I am not sure what I am doing wrong here.

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)

Alternate way using array_intersect() :

$testString = 'The cow jumped over the moon';
$userString = 'The cow';

$testStringArray = explode(' ', $testString);
$userStringArray = explode(' ', $userString);

$result = count( array_intersect($testStringArray, $userStringArray) ); // 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM