Question

I have some forbidden words, than are stored in database.

the things I need to do is to replace all of them byt a new words authorized.

I did something like that

//Inclusion du fichier à parser
require_once GETCASH_BASE_PATH . '/GESTION/pages_html/index.phtml'; // Layout principal
//Récupération du contenu
$buffer = ob_get_clean();


//Modification du contenu
$mots_interdits = censure();
while ($censure = mysql_fetch_assoc($mots_interdits)):
    $new = str_replace($censure['mot'], $censure['mot2'], $buffer);
endwhile;
//On affiche le nouveau contenu
echo $new;

the function is located in an other file

/**
 * fonction qui requete la censure
 * @return type
 */
function censure() {
    $query = "SELECT `mot`, `mot2` FROM `censure`";
    $result = mysql_query($query);
    return $result;
}

The trouble I have is that it replace only one forbidden words, I wish it could replace all words.

anykind of help will be much appreciated.

Was it helpful?

Solution

You have to give the $new value to the buffer after each str_replace, or you will only get the last censuration at the end

while ($censure = mysql_fetch_assoc($mots_interdits)):
    $new = str_replace($censure['mot'], $censure['mot2'], $buffer);
    $buffer = $new
endwhile;

OTHER TIPS

You can use arrays of words too:

$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

Your str_replace function is using $buffer as input, it does not modify it. You need to make sure as your loop iterates that you are using the current, already modified string as a your input to the str_replace function. Try something like this:

$mots_interdits = censure();
while ($censure = mysql_fetch_assoc($mots_interdits)):
    $buffer = str_replace($censure['mot'], $censure['mot2'], $buffer);
endwhile;

//On affiche le nouveau contenu echo $buffer;

Make use of preg_replace() instead of str_replace(),

 preg_replace($censure['mot'], $censure['mot2'], $buffer, 1); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top