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!

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

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能