以递归方式搜索数组值中的字符串值?

以递归方式搜索数组值中的字符串值?

问题描述:

new with recursive thing and i want to create search engine depend on value user typing and get it from array values all word in value that user typing

for example i have this array :

$array = array('it', 'pro', 'gram', 'mer', 'programmer');
$string = "itprogrammer";

sorry bad grammar. if anyone can help i appreciate it a lot. thanks you for your help.

new with recursive thing我想创建搜索引擎依赖于值用户输入并从数组值中获取所有单词 用户输入的值 p>

例如我有这个数组: p>

  $ array = array('it','pro',  'gram','mer','programmer'); 
 $ string =“itprogrammer”; 
  code>  pre> 
 
 

抱歉坏语法。 如果有人可以帮助我,我很感激。 谢谢你的帮助。 p> div>

You can use array_filter to filter out any values of the array which are not a substring of $string. Note I have used stripos for a case-insensitive search, if you want the search to be case-sensitive just use strpos instead.

$array = array('pro', 'gram', 'merit', 'program', 'it', 'programmer'); 
$string = "programit";
print_r(array_filter($array, function ($v) use($string) { return stripos($string, $v) !== false; }));

Output:

array
(
    [0] => pro
    [1] => gram
    [3] => program
    [4] => it
)

Update

Here is a recursive function which gives the same result.

function find_words($string, $array) {
    if (count($array) == 0) return $array;
    if (stripos($string, $array[0]) !== false)
        return array_merge(array($array[0]), find_words($string, array_slice($array, 1)));
    else
        return find_words($string, array_slice($array, 1));
}

Demo of both methods on rextester