user2250471
user2250471

Reputation: 1112

determine which word from an array is in a string

I have a string:

$str = "Hello is a greeting";

And I have an array of words:

$equals = array("is", "are", "was", "were", "will", "has", "have", "do", "does");

I'm trying to see which word is in the string:

$words = explode(" ", $str);
$new_association = false;
foreach($words as $word) {
    if(in_array($word, $equals)) {
        $new_association = true;
        $e['response'] = 'You made an association.';
        // determine which 'equals' word was used.      
        // $equal_used = 'is';
    }
}

How do I determine which equals word was used?

Upvotes: 0

Views: 34

Answers (2)

Eaten by a Grue
Eaten by a Grue

Reputation: 22931

Mark's answer above is superior but if you'd rather stick with your current approach:

$words = explode(" ", $str);
$new_association = false;
foreach($words as $word) {
    if(in_array($word, $equals)) {
        $new_association = true;
        $e['response'] = 'You made an association.';
        // determine which 'equals' word was used.      
        $equal_used = $word;
    }
}

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212402

$new_asscociation = false;
$equal_used = array_intersect($equals, explode(' ', $str)); 
if (!empty($equal_used)) { 
    $new_asscociation = true; 
    var_dump($equal_used); 
}

Upvotes: 2

Related Questions