dongrao9436
2018-10-04 03:08
浏览 45
已采纳

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

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.

图片转代码服务由CSDN问答提供 功能建议

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

例如我有这个数组:

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

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongtanghuan1885 2018-10-04 03:12
    已采纳

    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

    点赞 打赏 评论

相关推荐 更多相似问题