所以我不知道如何编写正则表达式来查找带有某些不重复字母的单词。
所以,如果说我想要字母为"elolh"的单词
那么这些将匹配:你好地狱lol
但这不会:eel(因为e重复了两次,但我提供的字母中只有1个e。
使用array_count_values
、array_walk
、str_split
和array_intersect_assoc
函数的"刚性"answers"简单"解决方案:
$pattern = "elolh";
$input = "hello eel lol heel ello";
function findValidWords($pattern, $input) {
$frequencies = array_count_values(str_split($pattern, 1));
$words = explode(" ", $input);
/**
* will compare character occurrence indices between the main "pattern"
* and each word from the input string
*/
array_walk($words, function(&$v) use($frequencies){
$counts = array_count_values(str_split($v, 1));
$compared = array_intersect_assoc($counts, $frequencies);
if (count($counts) != count($compared)) $v = "";
});
return array_filter($words);
}
$valid_words = findValidWords($pattern, $input);
print_r($valid_words);
输出:
Array
(
[0] => hello
[2] => lol
[4] => ello
)