2011-08-06 3 views
2

Quelqu'un peut-il suggérer comment je ferais ceci: Dites si j'ai eu la chaîne $text qui contient le texte entré par un utilisateur. Je veux utiliser une instruction 'if' pour trouver si la chaîne contient l'un des mots $word1$word2 ou $word3. Si ce n'est pas le cas, permettez-moi d'exécuter du code.Trouver des mots dans une chaîne

if (strpos($string, '@word1' OR '@word2' OR '@word3') == false) { 
    // Do things here. 
} 

J'ai besoin de quelque chose comme ça.

+0

Vous voulez exécuter si tous sont absents, ou au moins l'un d'entre eux est absent? – Dogbert

+0

duplication possible de [PHP - Si la chaîne contient l'un de ces mots] (http://stackoverflow.com/questions/6966490/php-if-string-contains-one-of-these-words) – hakre

+0

@Joey Morani: S'il vous plaît ne pas dupliquer les questions. – hakre

Répondre

2

Plus façon flexibile est d'utiliser le tableau de mots:

$text = "Some text that containts word1";  
$words = array("word1", "word2", "word3"); 

$exists = false; 
foreach($words as $word) { 
    if(strpos($text, $word) !== false) { 
     $exists = true; 
     break; 
    } 
} 

if($exists) { 
    echo $word ." exists in text"; 
} else { 
    echo $word ." not exists in text"; 
} 

Le résultat est: word1 existe dans le texte

2
if (strpos($string, $word1) === false && strpos($string, $word2) === false && strpos($string, $word3) === false) { 

} 
0

Comme dans mon previous answer:

if ($string === str_replace(array('@word1', '@word2', '@word3'), '', $string)) 
{ 
    ... 
} 
0

Il est peut-être préférable d'utiliser stripos au lieu de strpos car il est ca se-insensible.

0

vous pouvez utiliser preg_match, comme celui-ci

if (preg_match("/($word1)|($word2)|($word3)/", $string) === 0) { 
     //do something 
} 
1

Définir la fonction suivante:

function check_sentence($str) { 
    $words = array('word1','word2','word3'); 

    foreach($words as $word) 
    { 
    if(strpos($str, $word) > 0) { 
    return true; 
    } 
    } 

    return false; 
} 

Et l'invoquer comme ceci:

if(!check_sentence("what does word1 mean?")) 
{ 
    //do your stuff 
} 
Questions connexes