Link to home
Start Free TrialLog in
Avatar of EE-Member
EE-Member

asked on

PHP Replace text in file with synonym from dB

I am trying to PHP replace ANY & ALL word and phrase matches in a text file with associated synonyms from a dB and I had it doing single replaces ok but now I want multiple replaces I can't get it to replace at all :(

In the dB is a table with two fields per record:

seed         :  This is the match element to compare against and find occurences of in the text file.
synonym  :  This is a the partner field of the row conmtaining possible synonyms divided by a pipe | (random selection required)

example seed                 :   "100%"
example replacement     :  "100 per cent"
example field data text   :  "100 percent|one hundred pc|100pc"

The text file with the text to search and replace over is called doc.txt

My code (not working) so far is:

mysql_connect("localhost","wuser","p!as1@h");
mysql_select_db("words");

		$str=implode("\n",file('doc.txt'));
		$fp=fopen('doc.txt','w');

		$results = mysql_query("select * from synonyms");
		while ($row = mysql_fetch_assoc($results)) {

        $seed = $row[seed];
        $synonym = $row[synonym];

		$words = explode("|", $synonym);
		$index = rand(0, count($words)-1);
		$choice = $words[$index];

		while(strpos($str, '/$seed/') !== false) {
     	echo "Replacing $seed with $choice<br>";

		$str = str_replace($seed, $choice,$str);
		}
	}
    fwrite($fp,$str,strlen($str));

Open in new window


Could someone help this novice and show me what I need to do to make it check every line of the doc to see if there is any matches that should be replaced by synonyms?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of bombwriter
bombwriter
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of EE-Member
EE-Member

ASKER

Strange I kind of had that before and it would not work but now it does so thanks :)