简体   繁体   English

如果string包含任何字符,则从数组中删除元素

[英]Remove element from array if string contains any of the characters

Remove element from array if string contains any of the characters.For example Below is the actual array. 如果字符串包含任何字符,则从数组中删除元素。例如,下面是实际的数组。

array(1390) {
  [0]=>
  string(9) "Rs.52.68""
  [1]=>
  string(20) ""php code generator""
  [2]=>
  string(9) ""Rs.1.29""
  [3]=>
  string(21) ""php codes for login""
  [4]=>
  string(10) ""Rs.70.23""

 } 

I need the array to remove all the elements which start with RS. 我需要数组来删除所有以RS.开头的元素RS.

Expected Result 预期结果

 array(1390) {
      [0]=>
      string(20) ""php code generator""
      [1]=>
      string(21) ""php codes for login""


     } 

What i tried so far : 到目前为止我尝试了什么:

foreach($arr as $ll)
{

if (strpos($ll,'RS.') !== false) {
    echo 'unwanted element';
}

From above code how can i remove unwanted elements from array . 从上面的代码我如何从数组中删除不需要的元素。

You can get the $key in the foreach loop and use unset() on your array: 您可以在foreach循环中获取$key并在数组上使用unset()

foreach ($arr as $key => $ll) {
    if (strpos($ll,'RS.') !== false) {
        unset($arr[$key]);
    }
}

Note that this would remove none of your items as "RS" never appears. 请注意,这将不会删除任何项目,因为“RS”永远不会出现。 Only "Rs". 只有“Rs”。

This sounds like a job for array_filter . 这听起来像是array_filter的工作。 It allows you to specify a callback function that can do any test you like. 它允许您指定可以执行任何您喜欢的测试的回调函数。 If the callback returns true, the value if returned in the resulting array. 如果回调返回true,则返回结果数组中的值。 If it returns false, then the value is filtered out. 如果返回false,则过滤掉该值。

$arr = array_filter($arr, 
  function($item) { 
    return strpos($item, 'Rs.') === false; 
  });

Rs is different than RS you want to use stripos rather than strpos for non case sensitive checking Rs与RS不同,您希望使用stripos而不是strpos进行非区分大小写检查

foreach($arr as $key => $ll)
{    
  if (stripos($ll,'RS.') !== false) {
    unset($arr[$key]);
  }
}

or use arrayfilter as pointed out 或指出使用arrayfilter

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

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