Home > OS >  PHP Intersection of array containing substrings of another one
PHP Intersection of array containing substrings of another one

Time:05-04

I have these 2 arrays:

array(
  100 => 'this is some text',
  161 => 'prefix1 : this is some text',
  224 => 'some other text',
  356 => 'prefix2 : some other text',
  // ...
)

and

array(
  0 => 'prefix1',
  1 => 'prefix2',
  // ...
)

The first array should not contain the prefixes, so I would like to identify the errors like this as a result:

array(
  161 => 'prefix1 : this is some text',
  356 => 'prefix2 : some other text',
  // ...
)

CodePudding user response:

You can use array_filter with str_contains like:

$a = [
  100 => 'this is some text',
  161 => 'prefix1 : this is some text',
  224 => 'some other text',
  356 => 'prefix2 : some other text',
  ];


$b = ['prefix1','prefix2'];

print_r(array_filter($a, function($a) use ($b){
    foreach($b as $pref){
        if(str_contains($a, $pref)){
            return true;
        }
    }
}));

Output:

Array
(
    [161] => prefix1 : this is some text
    [356] => prefix2 : some other text
)

Example:

https://sandbox.onlinephpfunctions.com/c/c55a9

Reference:

  • Related