scarhand Posted March 10, 2009 Share Posted March 10, 2009 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? Link to comment https://forums.phpfreaks.com/topic/148855-replace-all-words-in-a-paragraph-with-content-from-database/ Share on other sites More sharing options...
scarhand Posted March 10, 2009 Author Share Posted March 10, 2009 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. Link to comment https://forums.phpfreaks.com/topic/148855-replace-all-words-in-a-paragraph-with-content-from-database/#findComment-781666 Share on other sites More sharing options...
premiso Posted March 10, 2009 Share Posted March 10, 2009 $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. Link to comment https://forums.phpfreaks.com/topic/148855-replace-all-words-in-a-paragraph-with-content-from-database/#findComment-781669 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.