是否正确使用preg_match来搜索包含特定字母的单词?

时间:2015-05-11 06:36:04

标签: php preg-match preg-match-all

我有一组信件,例如:

$word='estroaroint';

可以安排为像:

这样的词
- store
- train
- restoration
- ...etc

可以在我的文件列表'dictionary.txt'中找到它们。

一封信只能使用一次。

如何编写能够执行该操作的PHP脚本?

2 个答案:

答案 0 :(得分:0)

我会尝试使用此功能管理它:strpbrk() http://php.net/manual/en/function.strpbrk.php

答案 1 :(得分:0)

使用正则表达式一步到位是不可能的。但是,可以分两步完成:

  • 第一步找到字典中仅包含字母的所有单词。
  • 第二步过滤字母重复的单词。

示例(仅适用于ascii范围):

$pattern = '~\b[' . $word . ']{1,' . strlen($word) . '}+\b~';

if (preg_match_all($pattern, $dictionary, $m)) {
    $chars = count_chars ($word, 1);
    $result = array_filter($m[0], function ($i) use ($chars) {
        foreach (count_chars($i, 1) as $k=>$v) {
            if ($v > $chars[$k]) return false;
        }
        return true;
    });

    print_r($result);
}

PHP链接:array_filter - count_chars

注意:要将此脚本扩展为多字节字符,您需要编写自己的函数mb_count_chars(因为此函数不存在),它会拆分多字节字符串(例如,您可以使用{{1 }},mb_substr和循环,或mb_strlen preg_split~(?=.)~u选项)。您还需要将PREG_SPLIT_NO_EMPTY修饰符添加到正则表达式模式,并将u更改为其等效的多字节数。

相关问题