faq
faq

Reputation: 3086

Querying MySQL for anagrams

I have this script:

$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database,$db) or die( "Unable to select database");
mysql_query("set names 'utf8'");

$wordy = "pate";

$query = mysql_query("SELECT DISTINCT * FROM $db_table WHERE word LIKE '[pate]' ORDER BY word DESC");
$num = mysql_numrows($query); $i=0; 

while ($i < $num) {
    $word = mysql_result($query,$i,"word");

    echo $word." ";
    $i++;
}

$db_table contains English words. I want to echo out all possible anagrams; in this case it should echo tape pate peat. What query could I use to do this?

http://msdn.microsoft.com/en-us/library/ms179859.aspx <- here is a description

Upvotes: 2

Views: 986

Answers (2)

JJJ
JJJ

Reputation: 33143

If you can modify the table that contains the dictionary, run a script that adds a field for each entry that has the word with the letters it contains in alphabetical order. Then you can put the letters in the word you're searching similarly in alphabetical order and look for matches.

Tape, pate and peat would all look like "aept" when in alphabetical order, then you can do

$query = mysql_query("SELECT * FROM $db_table WHERE alpha = 'aept' ORDER BY word DESC");

Upvotes: 2

Gaurav Shah
Gaurav Shah

Reputation: 5279

I think first you must re arrange all the letters in the word to form an array

then do a sql query like :

SELECT DISTINCT * FROM $db_table WHERE word in ($array ) ORDER BY word DESC

got another idea :

you can do something like ...

SELECT DISTINCT * FROM $db_table WHERE word like '%$wordy[0]%' AND like '%$wordy[1]%' AND like '%$wordy[2]%' AND like '%$wordy[4]%' ORDER BY word DESC

Froe the comments I could suggest you use

length(word) = strlen($wordy)

Upvotes: 2

Related Questions