PHP: Get array values of a string array that match

2020-04-21 07:02发布

问题:

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 7 years ago.

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
)

回答1:

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.



回答2:

$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



回答3:

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.



回答4:

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


回答5:

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.