数组中的PHP数组搜索

Ben*_*ali 5 php arrays string-matching

$keywords = array('red', 'blue', 'yellow', 'green', 'orange', 'white');

$strings = array(
'She had a pink dress',
'I have a white chocolate',
'I have a green balloon',
'I have a chocolate shirt',
'He had a new yellow book',
'We have many blue boxes',
'I have a magenta tie');
Run Code Online (Sandbox Code Playgroud)

实际上strings阵列非常庞大(50k +条目).

什么是运行搜索和提取匹配的字符串的最佳方式

wor*_*fjr 4

最好的方法是使用array_filter().

$filtered_array = array_filter($strings,'filter');

function filter($a)
{
    $keywords = array('red', 'blue', 'yellow', 'green', 'orange', 'white');

    foreach ($keywords as $k)
    {
        if (stripos($a,$k) !== FALSE)
        {
            return TRUE;
        }
    }

    return FALSE;
}
Run Code Online (Sandbox Code Playgroud)