Find element of an array those contains only specific character set in PHP

前端 未结 1 724
北恋
北恋 2021-01-28 04:45

I need to find only the elements of an array that have a specific set of letters and any character before or after the set of letters.

I have arrays like these:

相关标签:
1条回答
  • 2021-01-28 05:29

    I am going to assume that you have already pre-filtered all strings to be either 4 or 5 characters long -- if not, you can uncomment my first filter function.

    Inputs:

    $findgroup=['eaten','enter','tend','sten','neat','dents','enet','netty','teeth','denet','teen','spent'];
    $values=['e','n','t'];
    

    Method:

    //$findgroup=array_filter($findgroup,function($v){return strlen($v)==4 || strlen($v)==5;});
    $findgroup=array_filter($findgroup,function($v)use($values){
        return
            sizeof(array_intersect(array_unique(str_split(substr($v,0,3))),$values))==3 ||
            sizeof(array_intersect(array_unique(str_split(substr($v,-3))),$values))==3;
    });
    var_export($findgroup);    
    // omitted: neat, dents, teeth, teen
    

    Output:

    array (
      0 => 'eaten',
      1 => 'enter',
      2 => 'tend',
      3 => 'sten',
      6 => 'enet',
      7 => 'netty',
      9 => 'denet',
      11 => 'spent',
    )
    
    0 讨论(0)
提交回复
热议问题