Jump to content

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.

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.