首页 > 解决方案 > 过滤数组以包含包含特定单词的所有字符串并检查是否有任何字符串匹配

问题描述

我试图从包含单词的数组中过滤字符串DEVICE

我使用了以下技术来检查数组中是否有一个叫做有设备的词,但它会打印

未找到匹配项

即使有包含单词 DEVICE 的字符串。

这是我尝试过的尝试:

$output= array('football GAME', 'cricket GAME', 'computer DEVICE','mobile DEVICE');
$string = 'DEVICE';
foreach ($output as $out) {
    if (strpos($string, $out) !== FALSE) {
        echo "Match found";
        return true;
    }
}
echo "Match Not found!";
return false;

所需输出:

输出应该是:

找到匹配。

而且我还想显示由以下单词组成的项目列表DEVICE

computer DEVICE  
mobile DEVICE

我在这里需要什么更正?

标签: phparraysfiltering

解决方案


您已经交换了strpos(). 要搜索的单词是函数中的第二个参数,字符串是第一个。

int strpos (string $haystack , mixed $needle [, int $offset = 0 ])

使用下面的代码获取所需的输出:

    $output= array('football GAME', 'cricket GAME', 'computer DEVICE','mobile DEVICE');
    $string = 'DEVICE';
    foreach ($output as $out) {
        if (strpos($out, $string) !== FALSE) {
              // You can also print the matched word using the echo statement below.
              echo "Match found in word: {$out} <br/>";
              return true;
        }
    }
    echo "Match Not found!";
    return false;

推荐阅读