如何将数组中的文本与字符串匹配,如果为true则返回其值?

时间:2017-09-02 13:00:59

标签: php arrays

我正在尝试理解如何将数组与一行文本匹配,如果找到数组中的文本,那么我想返回该值。

我尝试过以下但似乎没有回复。

Dog

按照这种逻辑,$catArray = array( '0' => 'breakfast', '1' => 'lunch', '2' => 'dinner', ); $text = 'It is your breakfast'; foreach($catArray as $cat){ if(strpos($cat, $text) !== false){ return $cat; } } 应该返回。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);
    }
}