具有某些未重复字符的单词的正则表达式

时间:2016-04-16 16:31:05

标签: php regex

因此,我无法弄清楚如何编写一个正则表达式来查找包含不可重复的字母的单词。

所以,如果我想说我想要字母和#34; elolh"

然后这些将匹配: 你好 地狱 洛尔

但这不会: 鳗鱼(因为e重复了两次,但我的信中只有1 e。

1 个答案:

答案 0 :(得分:0)

使用array_count_valuesarray_walkstr_splitarray_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
)