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:
$sample = array("sten", "netff", "enet", "denet");
$value = array('e', 'n', 't');
I need to find the values from the $sample
array which have 'e,n,t'
characters and single or double character before or after(either side, not both side) the match word. If I search with pattern e,n,t and 1 letter before or after(either side, not both side) it, the result will be
array("sten", "enet")
and if I search with pattern e,n,t and 2 letter before or after(either side, not both side) it, the result will be
array("netff", "denet")
I tried regex with preg_grep()
but it doesn't work:
1 letter before or after(either side, not both side):
$result = preg_grep("/^(?:.{1}".$value."|".$value.".{1})$/", $sample);
2 letter before or after(either side, not both side):
$result = preg_grep("/^(?:.{2}".$value."|".$value.".{2})$/", $sample);
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',
)