任何人都可以建議我如何做到這一點:說如果我有字符串$text
,其中包含用戶輸入的文本。我想使用'if語句'來查找字符串是否包含$word1
$word2
或$word3
之一。如果沒有,請允許我運行一些代碼。查找字符串中的單詞
if (strpos($string, '@word1' OR '@word2' OR '@word3') == false) {
// Do things here.
}
我需要類似的東西。
任何人都可以建議我如何做到這一點:說如果我有字符串$text
,其中包含用戶輸入的文本。我想使用'if語句'來查找字符串是否包含$word1
$word2
或$word3
之一。如果沒有,請允許我運行一些代碼。查找字符串中的單詞
if (strpos($string, '@word1' OR '@word2' OR '@word3') == false) {
// Do things here.
}
我需要類似的東西。
更多flexibile方法是使用單詞的數組:
$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";
}
的結果是:在文本
if (strpos($string, $word1) === false && strpos($string, $word2) === false && strpos($string, $word3) === false) {
}
存在正如我previous answer字1:
if ($string === str_replace(array('@word1', '@word2', '@word3'), '', $string))
{
...
}
可能更好地使用stripos
而不是strpos
,因爲它是ca SE-不敏感。
你可以使用的preg_match,這樣
if (preg_match("/($word1)|($word2)|($word3)/", $string) === 0) {
//do something
}
定義以下功能:
function check_sentence($str) {
$words = array('word1','word2','word3');
foreach($words as $word)
{
if(strpos($str, $word) > 0) {
return true;
}
}
return false;
}
並調用它像這樣:
if(!check_sentence("what does word1 mean?"))
{
//do your stuff
}
你想運行,如果所有的人缺席,或者其中至少有一個缺席? – Dogbert
可能重複的[PHP - 如果字符串包含這些詞之一](http://stackoverflow.com/questions/6966490/php-if-string-contains-one-of-these-words) – hakre
@Joey Morani:請不要重複提問。 – hakre