繁体   English   中英

如何在数组LIKE变量中生成If然后执行某些操作

[英]How to make If in array LIKE variable then do something

我有以下列表(示例代码,变量$ code_name):“A125”“B120”“C105”

还有一个数组($ codes_list),里面有很多代码,但还有一些额外的单词:“A125 NameA”“B8800 Ko”“B120 Name Bc”“D3030”

在for循环中,我可以检查数组中是否存在上述列表中的任何值($ code_name)。

if (in_array($code_name, $codes_list))
  {
    echo "Do nothing<br/>";
  } else {
    echo "Code is not in the list, create new one in DB: ".$code_name."<br/>";  
  }

我说的问题是$ code_name只包含“A125”。 但是在数组列表中添加了一些额外的文本“A125 NameA”。 所以结果将不是我想要的结果。

如果列表中的代码名称ALREADY EXISTS(例如A125,B120)则不执行任何操作。 如果它不存在(C105),则在DB中创建一个。

但我想要实现的是检查$ codes_list数组中的$ code_name LIKE %%。 所以我试图找到一个与mysql类似的功能。

那可能吗?

if (in_array(LIKE%'.$code_name.'%, $codes_list))

谢谢您的帮助

您可以使用preg_grep 您可以使用精确模式进行搜索。

  $check = preg_grep("/A125/", $codes_list);
  if (!empty($check))
  {
    echo "Do nothing<br/>";
  } else {
    echo "Code is not in the list, create new one in DB: ".$code_name."<br/>";  
  }

如果发现任何匹配, preg_grep将返回带有匹配元素的数组,否则将返回一个空数组。 您只需检查返回的数组是否为空。

$array = array("abc123 kj", "b45 kl", "f34");

var_dump(preg_grep("/abc123/", $array));

产量

array(1) {
  [0]=>
  string(9) "abc123 kj"
}

preg_grep

foreach($codes_list as $key => $value) {
if (strpos($value, $code_name) !== false) {
       //Do Nothing
    }
    else{

      //The code doesn't match

   }
}

另一种解决方案可能是:

if (strpos(implode( '§', $codes_list ),$code_name)===false) {
 echo "Code is not in the list, create new one in DB: ".$code_name."<br/>";  
} else {
 echo "Do nothing<br/>";
}

我想你正在寻找: -

    <?php
    $code_array = array("A125 NameA");
    $abc = 'A125';

    print_r( preg_grep( "/".$abc."/" , $code_array ) );

     $check = preg_grep( "/".$abc."/" , $code_array );
  if (!empty($check))
  {
    echo "Do nothing<br/>";
  } else {
    echo "Code is not in the list, create new one in DB: ".$code_name."<br/>";  
  }

    ?>

输出: - http://prntscr.com/79xylb

注意: - preg_grep将生成一个包含匹配元素的数组(如果找到任何匹配项),否则为空数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM