查找仅包含PHP中特定字符集的数组元素 [英] Find element of an array those contains only specific character set in PHP
问题描述
我只需要查找具有一组特定字母以及在该字母集合之前或之后的任何字符的数组元素.
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.
我有这样的数组:
$sample = array("sten", "netff", "enet", "denet");
$value = array('e', 'n', 't');
我需要从$sample
数组中找到具有'e,n,t'
个字符以及匹配词之前或之后(任一侧,而不是两侧)的单字符或双字符的值.如果我在模式e,n,t和前两个字母(任一侧,不是两面)之前搜索1个字母,则结果将为
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")
并且如果我在模式e,n,t和2字母的前后(任一侧,而不是两侧)搜索,结果将是
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")
我用preg_grep()
尝试了正则表达式,但不起作用:
I tried regex with preg_grep()
but it doesn't work:
前后有1个字母(双方,不是双方):
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);
推荐答案
我将假定您已经将所有字符串预先过滤为4或5个字符-如果没有,则可以取消对我的第一个过滤器的注释功能.
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.
输入:
$findgroup=['eaten','enter','tend','sten','neat','dents','enet','netty','teeth','denet','teen','spent'];
$values=['e','n','t'];
方法:
//$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
输出:
array (
0 => 'eaten',
1 => 'enter',
2 => 'tend',
3 => 'sten',
6 => 'enet',
7 => 'netty',
9 => 'denet',
11 => 'spent',
)
这篇关于查找仅包含PHP中特定字符集的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!