drwjv28028 2011-05-22 23:22
浏览 70
已采纳

Word Finder正则表达式,PHP和mySQL

I have a query that I'm trying to run against a database of words. The query must return a word that contains another word, and letters given. It is in PHP and mySQL.

For example:

Word Given: Cruel
Letters Given: abcdty

In the database, I need to find the word "Cruelty" based on the letters given, and the word given. It needs to works both ways. So if I had "atni" for letters, "Anticruel" would appear if it existed in the database.

I have it half working but the result given is not correct:

SELECT word
FROM words
WHERE LOCATE(  "cruel", word ) >0
AND word !=  "cruel"
AND word
REGEXP  '[ybilteh]'

The result set from this query:

"anticruelty"
"crueler"
"cruelest"
"crueller"
"cruellest"
"cruelly"
"cruelness"
"cruelnesses"
"cruelties"
"cruelty"

Update!!!

Thanks to Benjamin Morel, this is getting much closer.

This query:

SELECT word
FROM words
WHERE LOCATE(  "t", word ) >0
AND word !=  "t"
AND word
REGEXP  '^[ybilteh]*t[ybilteh]*$'
LIMIT 0 , 30

Finds words correctly. But also includes words with double letters. Such as "Beet". When only 1 "e" is available.

  • 写回答

1条回答 默认 最新

  • dream0776 2011-05-22 23:26
    关注

    Try this one:

    SELECT word
    FROM words
    WHERE word REGEXP '^[ybilteh]*cruel[ybilteh]*$'
    AND word != 'cruel';
    

    UPDATE: let's go refining with PHP, what about this?

    $word = 'cruel';
    $letters = 'ybilteh';
    
    $items = array("anticruelty", "crueler", "cruelest",
        "crueller", "cruellest", "cruelly", "cruelness",
        "cruelnesses", "cruelties", "cruelty");
    
    $letters = str_split($letters);
    foreach ($items as $item) {
        $list = $letters;
        // remove the original word (once)
        $thisItem = preg_replace("/$word/", '', $item, 1); 
        for ($i=0; $i<strlen($thisItem); $i++) {
            $index = array_search($thisItem[$i], $list);
            if ($index === false) {
                continue 2; // letter not available
            }
            unset($list[$index]); // remove the letter from the list
        }
        echo "$item
    "; // passed!
    }
    

    Returns: cruelly, cruelty

    You might probably find a better/simpler approach, but that should do the trick!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?