dogfighter Posted October 1, 2008 Share Posted October 1, 2008 I may have bitten off a bit more than I can chew this time. I have a string, and a database that's like a thesaurus. Column 1 is the root word and column 2 is a comma-separated list of words that it could be replaced with. Like this: ROOT REPLACEMENTS rain rain,snow,hail bird bird,cow,giraffe Lists of replacement "madlib" words are separated by commas, with no spaces. When I run the script, I want it to take the text in $sentence, find each root word, and replace that word with a random corresponding synonym. So for the string $sentence, <?php $sentence = "The rain in Spain stays mainly on the plain. A bird in the hand is worth two in the bush! Big bird!"; ?> And when I run the script, I would like it to find all instances the first root word from the DB ("rain") in $sentence and replace them with random corresponding replacement words ("rain", "snow" or "hail"). Then find the second root word ("bird") in $sentence and replace it with random corresponding replacement words ("bird", "cow" or "giraffe"). On and on until it goes through the whole database, which isn't very big anyway. When it's all done with this, I just want it to output the final result. So maybe the first "bird" becomes "cow" and the second "bird" becomes "giraffe". Or some other random combination. Every time my visitor hits refresh, whatever string they entered ($sentence) should be madlibbed using the root words in my database and random corresponding replacement words. I've posted what I have so far below, but at this point I'm stuck. For one thing, I can't just match " bird " because it won't always be surrounded by spaces (like in the third sentence). Sometimes it will be surrounded by a space and a period, a space and an exclamation point, a pair of double quotes, double quotes and a space, etc. Also, even when I do match that way, the first "bird" is always replaced by the same word that replaces the second "bird". I've been plugging away at this for two days now (hey, I'm a newbie) and I just feel like I'm getting nowhere. <?php // Omitted the part where I connect to the DB $var1 = mysql_query("SELECT `root` FROM `list`") or die (mysql_error()); // Select all root words from the madlib DB $sentence = "The rain in Spain stays mainly on the plain. A bird in the hand is worth two in the bush!"; //This is the string I want to match words in and replace. while($dbword = mysql_fetch_array($var1)){ $dbsyns = mysql_query("SELECT `synonyms` FROM `list` WHERE `root` = '".addslashes($dbword['root'])."'") or die (mysql_error()); // Get the comma-separated synonyms from the DB for the first root word $synonyms = mysql_fetch_array($dbsyns); $replacements = explode(",", $synonyms[0]); // Explode comma-separated synonyms to create array of synonyms $replaceshuffle = shuffle($replacements); // Shuffle the synonyms } ?> Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/ Share on other sites More sharing options...
Brian W Posted October 2, 2008 Share Posted October 2, 2008 I don't have time to right the script right now, but here is theory. Count how many words you have in the array from the database. get your array to work out like this $word[0] = crow $word[1] = sparrow ... then, use $i = rand(1,$the_count_of_words) $word[$i] will be a random word from your list. hope that helps Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655232 Share on other sites More sharing options...
dogfighter Posted October 2, 2008 Author Share Posted October 2, 2008 Thanks for the tip. I can explode the replacements and call them at random using shuffle, but I'm still miles away from anything resembling a solution. :-\ Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655233 Share on other sites More sharing options...
discomatt Posted October 2, 2008 Share Posted October 2, 2008 Did you want it to ignore contractions ( don't, won't, I'm, wouldn't... ect )? Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655240 Share on other sites More sharing options...
dogfighter Posted October 2, 2008 Author Share Posted October 2, 2008 Matt-- I've actually got those as root words in my DB, so don't could become do not, for example Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655241 Share on other sites More sharing options...
Brian W Posted October 2, 2008 Share Posted October 2, 2008 Thanks for the tip. I can explode the replacements and call them at random using shuffle, but I'm still miles away from anything resembling a solution. :-\ Oh well The only thing is that you will need to shuffle it for every time the word comes up any ways. About finding the word, I didn't think str_ireplace would care about what is on each side. Though, than again you may need to have spaces on each side in your pattern or there is a possibility that it will replace the word "cowardly" with "bovineardly", lol IDK, whats all this for anyways? are you making a weird version of Madlib? Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655254 Share on other sites More sharing options...
dogfighter Posted October 2, 2008 Author Share Posted October 2, 2008 Yeah it's actually for song lyrics, swaps out words. Sounds lame but the output will be pretty entertaining If it ever works Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655271 Share on other sites More sharing options...
Brian W Posted October 2, 2008 Share Posted October 2, 2008 LOl That does sound kinda entertaining. Hope that works out good, I want to try it when it is finished. Any ways, what do you have so far now? Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655277 Share on other sites More sharing options...
discomatt Posted October 2, 2008 Share Posted October 2, 2008 I've got something almost working. Sorry it's taking so long. At the bar watching the hockey game Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655290 Share on other sites More sharing options...
MasterACE14 Posted October 2, 2008 Share Posted October 2, 2008 You can do it the same way as my language filter script... same principle applies. <?php function filter_text($text) { // instead of grabbing the words from file, get them from database here $foul = file("curses.txt"); foreach ($foul as $curses) { $curses = trim($curses); if (preg_match("/".$curses."/i", $text)) { $wordlength = strlen($curses); for ($i = 1; $i <= $wordlength; $i++) { $repchar .= "*"; } $text = eregi_replace($curses, $repchar, trim($text)); $repchar = ""; } } // return the original text filtered of swearing return $text; } ?> Regards ACE Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655292 Share on other sites More sharing options...
Brian W Posted October 2, 2008 Share Posted October 2, 2008 Your at the bar and working on your project? Your crazy! lol I don't mean to rush you at all. Just would like to see a product, sounds like it could be fun. Where are you getting your replacement words or are you writing them yourself? Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655295 Share on other sites More sharing options...
discomatt Posted October 2, 2008 Share Posted October 2, 2008 Here's my take on it <pre><?php $link = mysql_connect( 'localhost', 'root', '' ); mysql_select_db( 'test', $link ); $str = "The rain in Spain stays mainly on the plain. A bird in the hand is worth two in the bush! Big bird!"; $obj = new getWords( $link ); if ( $obj->populate('madlib', 'root', 'replacements') ) print_r( $obj->replace($str) ); class getWords { protected $results = array(), $db = FALSE; public function __construct( $dbLink ) { $this->db = $dbLink; } public function populate( $table, $sourceCol, $replaceCol ) { $q = "SELECT `$sourceCol`, `$replaceCol` FROM `$table`"; $r = mysql_query( $q, $this->db ); if ( $r === FALSE ) return FALSE; while( $d = mysql_fetch_assoc($r) ) $this->results[ strtolower($d[$sourceCol]) ] = strtolower( $d[ $replaceCol ] ); if ( empty($this->results) ) return FALSE; return TRUE; } public function replace( $string ) { if ( empty($this->results) ) return $string; return preg_replace_callback( '%([a-z\']++)%i', array($this, 'replace_callback'), $string ); } protected function replace_callback ( $m ) { $lower = strtolower($m[1]); if ( array_key_exists($lower, $this->results) ) { $replace = explode( ',', $this->results[$lower] ); $m[1] = $replace[ array_rand($replace) ]; } return $m[1]; } } ?></pre> SQL -- -- Table structure for table `madlib` -- CREATE TABLE IF NOT EXISTS `madlib` ( `root` varchar(255) NOT NULL, `replacements` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `madlib` -- INSERT INTO `madlib` (`root`, `replacements`) VALUES ('rain', 'rain,snow,hail'), ('bird', 'bird,cow,giraffe'); Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655296 Share on other sites More sharing options...
MasterACE14 Posted October 2, 2008 Share Posted October 2, 2008 thats probably the best way to do it. But I don't think he will understand the OOP side of the script lol Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655299 Share on other sites More sharing options...
discomatt Posted October 2, 2008 Share Posted October 2, 2008 MasterACE14 -> TRy to avoid having RegEx calls in a loop if you can. Slows things down... especially when you're applying it to the entire sample text. You're better off using stripos to get offsets, then verifying that it isn't part of a string ( assignment has 'ass' in it for example ) with RegEx... that way if you HAVE to loop RegEx, you're only performing it on a small part of the sample text. Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655303 Share on other sites More sharing options...
redarrow Posted October 2, 2008 Share Posted October 2, 2008 example only....... <?php //array way......... $words=array("my name is redarrow and i love php"); $words=implode(' ',$words); $words_to_replace=array("redarrow","is","love"); $words_to_replace_to=array("john","was","like"); $result=str_replace($words_to_replace,$words_to_replace_to,$words); echo $result; ?> <?php //string with array $words="my name is redarrow and i love php"; $words_to_replace=array("redarrow","is","love"); $words_to_replace_to=array("john","was","like"); $result=str_replace($words_to_replace,$words_to_replace_to,$words); echo $result; ?> <?php // database way // daabase connection.... //my name is redarrow and i love php <<< in the word field //first field selected with limit.. $sql="SELECT * FROM words LIMIT 1"; $res=mysql_query($sql)or die(mysql_error()); while($words=mysql_fetch_assoc($res)){ $words_to_replace=array("redarrow","is","love"); $words_to_replace_to=array("john","was","like"); $result=str_replace($words_to_replace,$words_to_replace_to,$words['word']); echo $result; } ?> Link to comment https://forums.phpfreaks.com/topic/126692-replace-words-in-string-with-words-from-database/#findComment-655378 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.