Jump to content

Replace words in string with words from database.


dogfighter

Recommended Posts

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
Share on other sites

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
Share on other sites

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
Share on other sites

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
Share on other sites

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
Share on other sites

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
Share on other sites

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
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.