<?php
//.........................................................................
function getPhonemes($phonetics)
{
// Remove accents
$phonemesText = preg_replace("/[,']/", "", $phonetics);
// Break up the word into its phonemes
$phonemes = preg_split("/\\/+/", $phonemesText, -1,
PREG_SPLIT_NO_EMPTY);
return $phonemes;
}
// $rootPhonemes is an array of phonemes representing the word.
// $i is the number (counting from the end of the word) of phonemes
// you require to match before it's considered a rhyme.
function findRhymes($rootPhonemes, $i, $limit = NULL)
{
// Get the length of the sounds array
$num = count($rootPhonemes);
if($num == 0) return false;
// Make sure $i is within the range 1 to $num
if($i > $num) $i = $num;
else if($i < 1) $i = 1;
$i = $num - $i;
// Create an sql-ready regexp string that will match the current
// portion of the root word sounds that we want to look for.
// We want to exclude words that have already been listed:
if($i != 0 && $num > 1)
{
// This line does an sql-escape (i.e. \char -> [.char.])
$searchText = "(^|[^(".
preg_replace("/\\W/","[.\\0.]",
$rootPhonemes[$i - 1]).
"/)])/*";
}
else
{
$searchText = "/*";
}
for($j = $i; $j < $num; $j++)
{
// See comment above for explanation.
$searchText .= preg_replace("/\\W/","[.\\0.]",$rootPhonemes[$j]);
// We want this to match the end of the string. That's what the
// dollar sign is for.
if($j < $num - 1) $searchText .= "/+";
else $searchText .= "/*$";
}
// Plug our regexp string into the query.
$query = "SELECT * from rhymeDict WHERE ".
"replace(replace(phonetics,\",\",\"\"),\"'\",\"\") ".
"REGEXP BINARY \"$searchText\"";
// If there is a limit specified, select a maximum of one more than
// that limit (so we can tell whether there are more rows without)
// having to select every last one of them.
if($limit != NULL)
{
$query .= " LIMIT ".($limit + 1);
}
$result = mysql_query($query);
if($result && mysql_num_rows($result) != 0)
{
// Display the current phoneme match to the screen.
echo("<br>Matching last ".($num - $i)." sounds (".
join(array_slice($rootPhonemes,$i),"-")."):");
// Print out the table head.
echo("<table border=1 cellspacing=0".
" cellpadding=3 style=\"border-collapse: collapse;\">\n");
// Print out the table rows
// Go until
// 1. there are no more rows left in the result
// 2. the limit has been reached (if there is indeed a limit)
// whichever comes first.
$k = 0;
while(($row = mysql_fetch_row($result)) &&
($limit == NULL || $k < $limit))
{
echo("<tr><td>".$row[1]);
//echo(" (".$row[2].")");
echo("</td></tr>");
$k++;
}
// If the row we read last was not the last one:
if($row)
{
// Print a "View all..." link.
echo("<tr><td><small><a href=\"rhymer.php?phonetics=".
join($rootPhonemes,"-")."&num=".($num - $i).
"\" target=\"_blank\">View all...</a></small></td></tr>");
}
// Print out the table tail.
echo("</table>");
}
return true;
}
?>