5

ok i looked up some functions and i don't seem to lucky of finding any,

i wanna filter an array to strip specific array that contains some string

heres an example :

$array(1 => 'January', 2 => 'February', 3 => 'March',);
$to_remove = "Jan"; // or jan || jAn, .. no case sensitivity
$strip = somefunction($array, $to_remove);
print_r($strip);

it should return

[1] => February
[2] => March

a function that looks for the sub-string for all values in an array, if the sub-string is found, remove that element from the array

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Lili Abedinpour
  • 159
  • 1
  • 4
  • 12

3 Answers3

11

You can use array_filter and stripos

$array = array(1 => 'January', 'February', 'March');
print_r(array_filter($array, function ($var) { return (stripos($var, 'Jan') === false); }));
mpratt
  • 1,598
  • 12
  • 21
  • 1
    By using the stripos function, you should not have to worry about case sensitivity. – mpratt May 06 '12 at 21:10
  • one last question, how to only returns arrays that contains a specific string ? – Lili Abedinpour May 06 '12 at 21:25
  • Then Change the `=== false` with `!== false`. In this case `return (stripos($var, 'fEb') !== false)`. – mpratt May 06 '12 at 21:30
  • Hey, i have a question for you. Instead of making a new question i shall first try my luck here. What you wrote works perfectly however, how can i make it to specificly delete 'a' for example. Because if i run it like this it will also delete array entries which are `apple` or `banana`. If you don't mind be asking another question. What if the words im looking for is in an array named $common_words. So instead of just 'Jan' in your example I have a whole array of words. – Déjà vu Apr 11 '14 at 12:31
5

You can use array_filter() with a closure (inline-function):

array_filter(
  $array,
  function ($element) use ($to_remove) {
    return strpos($element, $to_remove) === false;
  }
);

(PHP Version >= 5.3)

dreftymac
  • 31,404
  • 26
  • 119
  • 182
MonkeyMonkey
  • 826
  • 1
  • 6
  • 19
-1

The simplest way is with array_filter. This function receives the array to filter and a callback function that does the actual filtering based on the value received:

function filter_func( $v )
{
  return ( ( $var % 2 ) == 0 );
}
$test_array = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 );
print_r( array_filter( $test_array, "filter_func" ) );

Hope helped!

felixgaal
  • 2,403
  • 15
  • 24