使用 Preg Grep:
$name = array('jake', 'rita', 'ali', 'addert', 'siryteee', 'skeueei', 'wsewwauie', 'aaaaweefio');
$vowels = array('a', 'e', 'i', 'o', 'u');
$pattern = '/('.implode('|',$vowels).'){3}/i';
print_r(preg_grep($pattern, $name));
输出
Array
(
[4] => siryteee
[5] => skeueei
[6] => wsewwauie
[7] => aaaaweefio
)
Sandbox
正则表达式非常严格
/(a|e|i|o|u){3}/i
将任何内容与以下a|e|i|o|u 的任意组合中的至少 3 个匹配。 (..) 是一个捕获组,| 是或者,{3} 是匹配 3 次。您可以使用{3,} 3 或更多,但在这种情况下并不重要,因为只要您有 3,您就可以很好地查看。 \i 标志使其不区分大小写。
只要每个数组项都是一个单词,这应该可以正常工作,如果您有多个单词,则很难找到匹配项。
仅用于循环
我会帮你的
$name = array('jake', 'rita', 'ali', 'addert', 'siryteee', 'skeueei', 'wsewwauie', 'aaaaweefio');
$vowels = array('a', 'e', 'i', 'o', 'u');
$matches = [];
for ($i = 0; $i < count($name); $i++) {
$total = 0;
for ($j = 0; $j < count($vowels); $j++) {
$total += substr_count($name[$i], $vowels[$j]);
if($total > 2){
$matches[] = $name[$i];
break; //exit inner loop
}
}
}
print_r($matches);
Sandbox
这里主要是
int substr_count ( 字符串 $haystack, 字符串 $needle [, int $offset = 0 [,整数 $length ]] )
substr_count() 返回 needle 子字符串在 haystack 字符串中出现的次数。请注意,needle 区分大小写。
http://php.net/manual/en/function.substr-count.php
与第一个输出相同。然而 Preg Grep 的好处(除了不区分大小写)是它保留了数组键,您可以通过在添加匹配项时添加 $i 索引在 for each 循环中复制它:
$matches[$i] = $name[$i];
这使匹配项与原始数组保持关联,这在某些情况下可能很有用。
如果您想要不区分大小写,最简单的方法就是将单词小写。在某些极端情况下这不起作用,但对于大多数英语单词来说应该没问题。
$name=strtolower($names[$i]);
//change $name to $names as it makes more sense
//when adding to the match array use $names[$i]
//that way we add the unmodified version to our matches
另外我应该从性能的角度提一下,通常最好在 for 循环(条件)之外进行计数。
$name_len = count($name);
for ($i = 0; $i < $name_len; $i++)
//another way to do it is like this
for($i=0,$n=count($name);$i<$n;$i++)
夏天
所以把所有东西放在一起
$names = array('jake', 'rita', 'ali', 'addert', 'siryteee', 'skeueei', 'wsewwauie', 'aaaaweefio');
$vowels = array('a', 'e', 'i', 'o', 'u');
$matches = [];
for ($i=0,$n=count($names);$i<$n;$i++) {
$total=0;
$name=strtolower($names[$i]);
for ($j=0,$v=count($vowels);$j<$v;$j++) {
//count lowercased version
$total += substr_count($name, $vowels[$j]);
if($total > 2){
$matches[$i] = $names[$i]; //use original in match
break; //exit inner loop
}
}
}
print_r($matches);
您将获得大约 12 行代码,相当于一次 preg_grep 调用。
最后一件事
您的代码只是将单词和元音转移到另一个数组。除了你会以words*vowels 更多的元音结束。因为对于外部 for 循环的每个循环(与单词相关),您需要对所有元音进行完整循环。
尽情享受吧!