【问题标题】:How to check array data that matches from random characters in php?如何检查与php中随机字符匹配的数组数据?
【发布时间】:2018-10-09 10:47:52
【问题描述】:

我有一个如下的数组:

$fruits = array("apple","orange","papaya","grape")

我有一个像下面这样的变量:

$content = "apple";

我需要过滤一些条件,比如:如果这个变量至少匹配一个数组元素,做一些事情。变量$content 是一组随机字符,实际上是数组数据中可用的字符之一,如下所示:

$content = "eaplp"; // it's a dynamically random char from the actual word "apple`

我所做的如下:

$countcontent = count($content);

for($a=0;$a==count($fruits);$a++){

      $countarr = count($fruits[$a]);

      if($content == $fruits[$a] && $countcontent == $countarr){
          echo "we got".$fruits[$a];
      }

}

当字符串中的总单词与数组数据之一的总单词匹配时,我试图计算这些短语有多少个字母,并且像 if...else... 一样,但除此之外我们还能做些什么吗?

【问题讨论】:

  • 当多个单词可以映射到随机字母数组时,你想如何处理?
  • 对于我的情况,我只需要从数组中的整个单词中搜索一个单词,因为只有一个单词与随机单词@sevavietl 匹配,没有多个单词类似于 apple custardapple pie 。仅限apple
  • in_array() ...

标签: php arrays search


【解决方案1】:

如何循环遍历数组,并使用一个标志来查看它是否匹配?

$flag = false;

foreach($fruits as $fruit){
    if($fruit == $content){
        $flag = true;
    }
}

if($flag == true){
    //do something
}

【讨论】:

  • $content 是一个随机字符......所以这个东西是可行的,但它看起来和我试过的很相似......
【解决方案2】:

我们可以使用in_array 检查数组是否包含某个值。所以你可以检查你的$fruits数组是否包含字符串"apple"

in_array("apple", $fruits)

返回一个布尔值。

如果字母的顺序是随机的,我们可以用这个函数按字母顺序对字符串进行排序:

function sorted($s) {
    $a = str_split($s);
    sort($a);
    return implode($a);
}  

然后将此函数映射到您的数组并检查它是否包含已排序的字符串。

$fruits = array("apple","orange","papaya","grape");
$content = "eaplp";
$inarr = in_array(sorted($content), array_map("sorted", $fruits));

var_dump($inarr);
//bool(true)

另一个选项是array_search。使用array_search 的好处是它返回项目的位置(如果它在数组中找到,否则false)。

$pos = array_search(sorted($content), array_map("sorted", $fruits));

echo ($pos !== false) ? "$fruits[$pos] found." : "not found.";  
//apple found.

【讨论】:

  • 如何回显“发现苹果”或“发现木瓜”之类的结果?我知道 tgat 结果将是“真实的”,但我如何回应真实的话?我的意思不是给定的随机字符
  • 您必须遍历数组或使用array_search。我会更新我的答案。
【解决方案3】:

这也将起作用,但方式略有不同。

我将字符串拆分为数组并对它们进行排序以匹配每个人。
然后我使用 array_slice 仅匹配 $content 中的字符数,如果它们匹配它就是匹配。
这意味着这将以“松散”的方式与“苹果汁”或“苹果凝乳”匹配。

不确定这是否需要,但认为它可能对某人有用。

$fruits = array("apple","orange","papaya","grape","apple juice", "applecurd");
$content = "eaplp";
$content = str_split($content);
$count = count($content);

Foreach($fruits as $fruit){
    $arr_fruit = str_split($fruit);
    // sort $content to match order of $arr_fruit
    $SortCont = array_merge(array_intersect($arr_fruit, $content), array_diff($content, $arr_fruit));
    // if the first n characters match call it a match
    If(array_slice($SortCont, 0, $count) == array_slice($arr_fruit, 0, $count)){
        Echo "match: " . $fruit ."\n";
    }
}

输出:

match: apple
match: apple juice
match: applecurd

https://3v4l.org/hHvp3
它的速度也与 t.m.adams 答案相当。有时更快有时更慢,但请注意此代码如何找到多个答案。 https://3v4l.org/IbuuD

【讨论】:

    【解决方案4】:

    这是一个干净的方法。如果找到,则尽早返回未加密的值,否则返回 null。仅返回完全匹配。

    function sortStringAlphabetically($stringToSort)
    {
        $splitString = str_split($stringToSort);
        sort($splitString);
    
        return implode($splitString);
    }
    
    function getValueFromRandomised(array $dataToSearch = [], $dataToFind)
    {
        $sortedDataToFind = sortStringAlphabetically($dataToFind);
    
        foreach ($dataToSearch as $value) {
            if (sortStringAlphabetically($value) === $sortedDataToFind) {
                return $value;
            }
        }
    
        return null;
    }
    
    $fruits = ['apple','orange','papaya','grape'];
    $content = 'eaplp';
    
    $dataExists = getValueFromRandomised($fruits, $content);
    
    var_dump($dataExists);
    // string(5) "apple" 
    

    未找到示例:

    $content = 'eaplpo';
    var_dump($dataExists);
    // NULL
    

    然后你可以像这样使用它(例如):

    echo !empty($dataExists) ? $dataExists . ' was found' : 'No match found';
    

    注意:这是区分大小写的,这意味着它不会从“eaplp”中找到“Apple”。这可以通过在循环的条件变量上执行 strtolower() 来解决。

    【讨论】:

      【解决方案5】:

      我喜欢 t.m.adams 的回答,但我也有解决这个问题的方法:

      array_search_random(string $needle, array $haystack [, bool $strictcase = FALSE ]);

      说明:在数组元素中搜索字符串,而不考虑字符在元素中的位置。

      • needle:作为字符串查找的字符
      • haystack:要搜索的数组
      • strictcase:如果设置为 TRUE,“mood”将匹配“mood”和“doom”,但不匹配“Mood”和“Doom”,如果设置为 FALSE(=default),它将匹配所有这些。

      功能:

       function array_search_random($needle, $haystack, $strictcase=false){
      
        if($strictcase === false){
         $needle = strtolower($needle);     
        }
      
        $needle = str_split($needle);
                  sort($needle);
        $needle = implode($needle);
      
        foreach($haystack as $straw){
      
         if($strictcase === false){
          $straw = strtolower($straw);     
         }
      
         $straw = str_split($straw);
                  sort($straw);
         $straw = implode($straw);
      
         if($straw == $needle){
          return true;
         }
      
        }
      
        return false;
      
       }
      

      【讨论】:

        【解决方案6】:

        我认为这是回答这个问题的最简单方法。上面的一些算法似乎“矫枉过正”。

        $fruits = array("apple","orange","papaya","grape");
        $content = "eaplp";
        
            foreach ($fruits as $key => $fruit) {
                $fruit_array = str_split($fruit); // split the string into array
                $content_array = str_split($content); // split the content into array
        
                // check if there's no difference between the 2 new array
                if ( sizeof(array_diff($content_array, $fruit_array)) === 0 ) {
                    echo "we found the fruit at key: " . $key;
                    return;
                }
            }
        

        【讨论】:

        • 现在这个真的很好! array_diff().. 没想到这个 :)
        • @Bernhard 谢谢,没有必要让事情复杂化,而且它确实更具可读性。 :)
        【解决方案7】:

        如果只使用原生 PHP 函数呢?

        $index = array_search(count_chars($content), array_map('count_chars', $fruits));
        

        如果$index 不为空,您将获得$content$fruits 中的位置。

        附:请注意,count_chars 可能不是解决该问题的最快方法。

        【讨论】:

          【解决方案8】:

          使用随机标记来搜索数组中的值,您会遇到误报问题。根据用例,这可能会产生误导性结果。

          在搜索情况下,例如输入错误的单词,我会实现一个过滤器解决方案,它会产生一个匹配的数组。如有必要,可以通过计算levenshtein 距离对结果进行排序,以获取最可能的结果。

          字符串长度解决方案

          非常容易实现。

          误报:几乎每个长度相同的字符串(如 applegrape)都会匹配。

          例子

          $matching = array_filter($fruits, function ($fruit) use ($content) {
              return strlen($content) == strlen($fruit);
          });
          if (count($matching)) {
              // do your stuff...
          }
          

          正则表达式解决方案

          它比较字符串长度并以有限的方式包含字符。实施适中,在大数据案例上表现良好。

          误报:像abc 这样的内容将匹配bac,但也匹配bbb

          示例

          $matching = preg_grep(
               '#['.preg_quote($content).']{'.strlen($content).'}#',
                $fruits
          );
          if (count($matching)) {
              // do your stuff...
          }
          

          字母数字排序解决方案

          在使用 PHP 的性能方面最准确但也是一种缓慢的方法。

          误报:像abc 这样的内容会匹配baccab

          示例

          $normalizer = function ($value) {
              $tokens = str_split($value);
              sort($tokens);
              return implode($tokens);
          };
          $matching = array_filter($fruits, function ($fruit) use ($content, $normalizer) {
              return ($normalizer($fruit) == $normalizer($content));
          });
          if (count($matching)) {
              // do your stuff...
          }
          

          【讨论】:

            【解决方案9】:

            if(in_array("苹果", $fruits)){ 真实的陈述 }别的{ 否则声明 }

            【讨论】:

            • 请编辑您的答案并添加更多描述,并请为脚本使用正确的标记代码
            猜你喜欢
            • 2023-03-27
            • 1970-01-01
            • 1970-01-01
            • 2020-12-04
            • 2019-08-22
            • 2015-05-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多