使用PHP删除匹配特定字符串的数组中的所有元素

时间:2022-12-28 20:22:03

I'm hoping this is really simple, and I'm missing something obvious!

我希望这很简单,我错过了一些明显的东西!

I'm trying to remove all elements in an array that match a certain string. It's a basic 1D array.

我正在尝试删除数组中与某个字符串匹配的所有元素。这是一个基本的1D阵列。

array("Value1", "Value2", "Value3", "Remove", "Remove");

I want to end up with

我想结束

array("Value1", "Value2", "Value3");

Why does array_filter($array, "Remove"); not work?

为什么是array_filter($ array,“Remove”);不行?

Thanks.

2 个解决方案

#1


11  

You can just use array_diff here, if it's one fixed string:

你可以在这里使用array_diff,如果它是一个固定的字符串:

$array = array_diff($array, array("Remove"));

For more complex matching, I'd use preg_grep obviously:

对于更复杂的匹配,我明显使用preg_grep:

$array = preg_grep("/^Remove$/i", $array, PREG_GREP_INVERT);
// matches upper and lowercase for example

#2


3  

You need to use a callback.

您需要使用回调。

array_filter($array, function($e){
   return stripos("Remove", $e)===false
});

To understand above code properly see this commented code.

要正确理解上面的代码,请参阅此注释代码。

array_filter($array, function($e){
    if(stripos("Remove", $e)===false) // "Remove" is not found
        return true; // true to keep it.
    else
        return false; // false to filter it. 
});

#1


11  

You can just use array_diff here, if it's one fixed string:

你可以在这里使用array_diff,如果它是一个固定的字符串:

$array = array_diff($array, array("Remove"));

For more complex matching, I'd use preg_grep obviously:

对于更复杂的匹配,我明显使用preg_grep:

$array = preg_grep("/^Remove$/i", $array, PREG_GREP_INVERT);
// matches upper and lowercase for example

#2


3  

You need to use a callback.

您需要使用回调。

array_filter($array, function($e){
   return stripos("Remove", $e)===false
});

To understand above code properly see this commented code.

要正确理解上面的代码,请参阅此注释代码。

array_filter($array, function($e){
    if(stripos("Remove", $e)===false) // "Remove" is not found
        return true; // true to keep it.
    else
        return false; // false to filter it. 
});