【问题标题】:PHP check if a variable is LIKE an item in an array using in_arrayPHP使用in_array检查变量是否像数组中的项目
【发布时间】:2014-08-02 22:25:18
【问题描述】:

我正在使用以下代码创建这个数组:

$ignored = array();
foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
    $ignored[] = $ignored2;
}

我想检查数组中的任何项目是否像变量一样。到目前为止我有这个:

if(in_array($data[6], $ignored)) {

但我不确定如何处理 LIKE

【问题讨论】:

  • 明确like的含义。不区分大小写?
  • 类似于 SQL 查询(SELECT * from table where col1 LIKE %...%)
  • 有点像或一模一样 LIKE?
  • 那么这是否包括处理通配符,ahem,LIKE '%term%'?你需要解释你在寻找什么规则。
  • 在你的 foreach 循环中,添加一个 strpos 函数来检查变量是否“喜欢” $ignored2 : strpos($ignored2, $myVariable) !== false

标签: php


【解决方案1】:

in_array() 不提供这种类型的比较。您可以按如下方式制作自己的功能:

<?php
function similar_in_array( $sNeedle , $aHaystack )
{

    foreach ($aHaystack as $sKey)
    {
        if( stripos( strtolower($sKey) , strtolower($sNeedle) ) !== false )
        {
            return true;
        }
    }    
    return false;
}
?>

您可以将此功能用作:

if(similar_in_array($data[6], $ignored)) {
    echo "Found";   // ^-search    ^--array of items
}else{              
    echo "Not found";
}

函数参考:

  1. stripos()
  2. strtolower()
  3. in_array()

【讨论】:

    【解决方案2】:

    好吧,like 实际上是来自 SQL 世界。 你可以使用这样的东西:

      $ignored = array();
      foreach(explode("\n", $_POST["ignored"]) as $ignored2) {
          $ignored[] = $ignored2;
          if ( preg_match('/^[a-z]+$/i', $ignored2) ) {
             //do what you want...
          }
      }
    

    更新:嗯,我找到了这个答案,可能是你需要的:

    Php Search_Array using Wildcard

    【讨论】:

    • 我想在 foreach 循环之外运行 if 语句
    【解决方案3】:

    这是一种方法,可以是customized fairly easily,使用lambda function:

    $words = array('one','two','three','four');
    $otherwords = array('three','four','five','six');
    
    while ($word = array_shift($otherwords)) {
        print_r(array_filter($words, like_word($word)));
    }
    
    function like_word($word) {
        return create_function(
            '$a', 
            'return strtolower($a) == strtolower(' . $word . ');'
        );
    }
    

    http://codepad.org/yAyvPTIq

    要添加不同的检查,只需向return 添加更多条件。在单个函数调用中完成:

    while ($word = array_shift($otherwords)) {
        print_r(find_like_word($word, $words));
    }
    
    function find_like_word($word, $words) {
        return array_filter($words, like_word($word));
    }
    
    function like_word($word) {
        return create_function(
            '$a', 
            'return strtolower($a) == strtolower(' . $word . ');'
        );
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多