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
)
4
  • 5
    What do you have so far? Commented Dec 7, 2012 at 16:19
  • 1
    Wow, this works better than coders for hire! Commented Dec 7, 2012 at 16:27
  • 2
    @jeroen everyone is keen to jump on low hanging fruit like this. Gotta get them rep points! Commented Dec 7, 2012 at 17:19
  • See also: stackoverflow.com/questions/12543361/… Commented Aug 24, 2019 at 22:53

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't really understand the "function($item) use($substrings)" part, but it works fine. Thank you!
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

Comments

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.

Comments

0
$arr=array();
foreach($substrings as $item)
{
    $result=array_keys($strings,$item);
    if ($result)
    {
        $arr=array_merge($arr,$result);
    }
}

1 Comment

This would work for matching the whole of a string, but not for partial matches such as 'pp' and 'rang' as was mentioned.
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.

2 Comments

Be careful, strstr might return the string "0" which is considered false-y
@knittl Ah, didn't consider the case where a substring might be "0". Thanks, I fixed it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.