2013-07-02 50 views
0

你能告訴我如何使用strops來查看一個字符串是否不包含任何兩個特定的單詞? (?ifstrpos找到多個單詞?

$phrase = 「how to use strops?」 
if(strpos($phrase, "?|if") === false) //Is there a way I can detect the presence of 
{    //either words in a sentence using one line of code that has strpos 

    echo 「neither word is found」; 
} 
+1

'strpos'告訴你在另一個字符串字符串的第一次出現它可能不是在這裏使用的最佳選擇。如果你想使用它,你需要使用它兩次,一次是'?',一次是'if'。 –

+1

你不能只用'preg_match'嗎?'preg_match('/ \?| if /',$ phrase);' – sbeliv01

+0

「使用具有strpos的一行代碼」聽起來有點像家庭作業,你還應該注意到「strpos」沒有檢測到「words」,它檢測到了出現「if」會匹配「 (strpos($ phrase,「?」)|| strpos($ phrase,「if」))=== false)是一條線。 –

回答

2

strpos()不支持正則表達式。所以,你要麼使用正則表達式(如preg_match()或不喜歡那麼複雜的東西:

$phrase = "how to use strpos"; 
$words = array('foo', 'bar'); 

$matches = 0; 
foreach($words as $word) { 
    $matches += (strpos($phrase, $word) !== false) ? 1 : 0; 
} 

printf("%d words matches", $matches); 
-2
if ((strpos($phrase, "?")===FALSE)$$(strpos($phrase,"if")===FALSE)) echo "neither word is found"; 
+0

'strpos'可以返回'0',這意味着「字符串的開始」。你應該使用'strpos()=== FALSE' * NOT *'!strpos()'。 –

+0

沒有注意到。謝謝你,併爲我的錯誤答案感到抱歉! –