因此,我无法弄清楚如何编写一个正则表达式来查找包含不可重复的字母的单词。
所以,如果我想说我想要字母和#34; elolh"
然后这些将匹配: 你好 地狱 洛尔
但这不会: 鳗鱼(因为e重复了两次,但我的信中只有1 e。
答案 0 :(得分:0)
使用array_count_values
,array_walk
,str_split
和array_intersect_assoc
函数的“刚性”和“简单”解决方案:
$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
)