开发者

Word Finder regular expression, 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 a开发者_如何学编程nother 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.


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\n"; // passed!
}

Returns: cruelly, cruelty

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜