2

There are two arrays:

$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');

I want to get an array which contains all the strings, that match the substrings:

Array
(
    [0] => Apple
    [2] => Orange
)

Or with new indices:

Array
(
    [0] => Apple
    [1] => Orange
)
Ben
  • 1,550
  • 1
  • 16
  • 24

5 Answers5

5

A simple solution that comes to mind: combine array_filter and strpos;

$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');

$result = array_filter($strings, function($item) use($substrings) {
  foreach($substrings as $substring)
    if(strpos($item, $substring) !== FALSE) return TRUE;
  return FALSE;
});

To reset indices, you can use the array_values function.

knittl
  • 246,190
  • 53
  • 318
  • 364
1
$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');
$newarray = array();

foreach ($strings as $string) {
    foreach ($substrings as $substring) {
        if (strstr($string, $substring)) {
            array_push($newarray, $string);
        }
    }
}

in $newarray you have the result

Baronth
  • 981
  • 7
  • 13
0

You can use array_filter for this:

$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');

$result = array_filter($strings, function($string) use ($substrings){
    foreach($substrings as $substring)
        if(strstr($string, $substring) !== false)
            return true;
    return false;
});

// $result is the result you want.
Paul
  • 139,544
  • 27
  • 275
  • 264
0

try array_search. looked at the second note at the bottom of this page http://php.net/manual/en/function.array-search.php for an example.

Colby Guyer
  • 594
  • 3
  • 14
0
$arr=array();
foreach($substrings as $item)
{
    $result=array_keys($strings,$item);
    if ($result)
    {
        $arr=array_merge($arr,$result);
    }
}
Mert Emir
  • 691
  • 1
  • 8
  • 20
  • This would work for matching the whole of a string, but not for partial matches such as 'pp' and 'rang' as was mentioned. – RobMasters Dec 07 '12 at 16:31