代码之家  ›  专栏  ›  技术社区  ›  Dixon Chaudhary

在PHP中从数组中过滤特定单词

  •  0
  • Dixon Chaudhary  · 技术社区  · 7 年前

    我试图从包含单词DEVICE的数组中筛选字符串。

    电流输出:

    我使用了以下技术来检查数组中是否有一个名为having DEVICE的单词,但它会打印

    未找到匹配项

    即使有字符串有单词设备。

    以下是我的尝试:

    <?php
        $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组成的,比如:

    计算机设备
    移动设备

    我这里需要什么更正?我们非常感谢你的建议。

    4 回复  |  直到 7 年前
        1
  •  2
  •   Andreas    7 年前

    解决这个问题的一种非循环方法是使用preg_grep,它是数组上的regex。
    模式以不区分大小写的方式搜索“device”,并返回任何包含device的字符串。

    $output= array('football GAME', 'cricket GAME', 'computer DEVICE','mobile DEVICE');
    $string = 'DEVICE';
    $devices = preg_grep("/" . $string . "/i", $output);
    Var_dump($devices);
    

    输出

    array(2) {
      [2]=>
      string(15) "computer DEVICE"
      [3]=>
      string(13) "mobile DEVICE"
    }
    

    https://3v4l.org/HkQcu

        2
  •  2
  •   Abhay Padda    7 年前

    你已经交换了 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;
    
        3
  •  1
  •   rmoro    7 年前

    你的立场与斯特普斯的论点相反。来自php.net:

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

    因此,您应该将第5行替换为以下内容

     if (strpos($out, $string) !== FALSE) {
    

    [一] https://secure.php.net/manual/en/function.strpos.php

        4
  •  1
  •   Phil    7 年前

    你的问题是 strpos() 争论是倒退的。这个 API

    int strps(字符串$haystack,混合$needle[,int$offset=0])


    至于你的另一个问题。。。

    …我还想显示由单词DEVICE组成的项目列表

    您可以通过 array_filter()

    $string = 'DEVICE';
    $filtered = array_filter($output, function($out) use ($string) {
        return strpos($out, $string) !== false;
    });
    
    echo implode(PHP_EOL, $filtered);
    if (count($filtered) > 0) {
        echo 'Match found';
        return true;
    }
    echo 'Match Not found!';
    return false;
    
    推荐文章