2017-09-02 84 views
0

我想了解如何匹配一個文本行的數組,如果發現數組內的文本,然後我想返回該值。如何匹配數組中的文本到一個字符串,並返回它的值如果爲true?

我試過以下,但似乎沒有得到返回。

$catArray = array(
    '0' => 'breakfast', 
    '1' => 'lunch', 
    '2' => 'dinner', 
); 

$text = 'It is your breakfast'; 

foreach($catArray as $cat){ 
    if(strpos($cat, $text) !== false){ 
     return $cat; 
    } 
} 

通過這個邏輯,breakfast應該返回。

+3

你有參數傳遞給strpos以錯誤的方式 – Clive

+1

從http://php.net/manual/en/function.strpos.php,對strpos簽名是'混合strpos(字符串$大海撈針,混合$針[,int $ offset = 0])'。試試'strpos($ text,$ cat)'。 – Nima

+0

大聲笑..我老實說起了超過27個小時,眼睛模糊,我覺得像一個白癡錯過這樣的事情..謝謝@ Clive和尼瑪 – Craig

回答

0
$catArray = array(
    '0' => 'breakfast', 
    '1' => 'lunch', 
    '2' => 'dinner', 
); 
$text = 'It is your breakfast'; 

foreach($catArray as $cat){ 
    if(strpos($text, $cat) !== false){ 
     echo $cat; 
    } 
} 

回報 breakfast

所以基本上扭轉haystack and the needle

0

你正在做它在一個錯誤的方式,你也正在返回變量,而不是印刷。 這裏是正確的語法:

strpos(<srting>,<find>,<start-optional>) 

我修改代碼,現在它正在工作。

$catArray = array(
    '0' => 'breakfast', 
    '1' => 'lunch', 
    '2' => 'dinner', 
); 

$text = 'It is your breakfast'; 

foreach($catArray as $cat){ 
    if(strpos($text, $cat) !== false){ 
     echo($cat); 
    } 
} 
相關問題