Jump to content

replace all words in a paragraph with content from database


scarhand

Recommended Posts

im trying to replace all the occurences of a words inside of an article i have written if they exist in the database.

 

the word will be replaced with a random synonym from an imploded array taken from the database row where that word is

 

the database table structure contains "word" and "synonyms" columns. synonyms is a comma-seperated list.

 

heres the code:

 

<?php

$article = (a large article i have written);

$arwords = explode(' ', $article);

foreach ($arwords as $arword)
{
$arword = mysql_real_escape_string($arword);

$sql = mysql_query("select synonyms from words where word='$arword'");

if (mysql_num_rows($sql) != 0)
{
$syn = mysql_result($sql, 0);
$syna = explode(',', $syn);
$randsyn = array_rand($syna);

$article = str_replace($arword, $randsyn, $article);
}
}
?>

 

This code is returning some funky stuff. Little help?

I am close:

 

<?php

$sql = mysql_query("select * from words");

$words = array();
$synonyms = array();

while ($row = mysql_fetch_array($sql))
{
  $words[] = $row['word'];
  $syns = explode(',', $row['synonyms']);
  $randsyn =  array_rand($syns);
  $synonyms[] = $syns[$randsyn];
}

$article = str_replace($words, $synonyms, $article);

echo "<font style=\"color: red;\">$article</font>";

 

The problem now, is that it is making the replacements EVERYWHERE, even inside of words.

$article = str_replace(" " . $words . " ", $synonyms, $article);

 

Will make it only replace words that have a space before and after (this may not be what you want due to periods etc.)

 

For a more advanced replace, look into preg_replace.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.