1
votes

I'm trying to create a comment system using php that replaces a commenters bad words with ****. I'm using sql and have a database with two columns, one with the bad word and one with the replacement word (which is the ****). So far, I am able to identify when a user types in a determined bad word and retrieve the replacement word for it, however I am unable to replace that bad word with the replacement word. I tried to do $element = $goodWord after $goodWord = $row['replaceWord'] to say that the new identified bad word should be replaced, however it does nothing. I'm not exactly sure how to set an element within an array in php to a new value. Any suggestions?

code:

if(!empty($_GET["field1_name"])) {
    $field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
    $field1_name_array = explode(" ",$field1_name);

    foreach($field1_name_array as $element){
        $query = "SELECT replaceWord FROM changeWord WHERE badWord = '$element' ";
        $query_link = mysqli_query($link,$query);
        if(mysqli_num_rows($query_link)>0){
            $row = mysqli_fetch_assoc($query_link);
            $goodWord = $row['replaceWord'];
            $element = $goodWord
        }
    }
}
1
where do you want make the replace , to db ?? Are you saving the comment to table ? - ck_arjun
yes, I want to save to the database. I have another table that stores in comments so I'd like to store in the filtered comment with the ****. The table has two columns, an ID column and a COMMENTS column. - Oviya Arasu
What's the code after your shown code? Do you change back $field1_name_array with new $element? - Tuan Duong
I edited the code. I just added one line at the end of the loop - Oviya Arasu
Then you need to make reference on $element by putting & : foreach ($field1_name_array as &element). Or using key foreach ($field1_name_array as $key => $element) {... $field1_name_array[$key] = $goodWord;}. Don't forget to implode $field1_name_array after foreach before inserting to database. - Tuan Duong

1 Answers

2
votes
if(!empty($_GET["field1_name"])) {
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
$newComment = '';
foreach($field1_name_array as $element){
    $query = "SELECT replaceWord FROM changeWord WHERE badWord = '$element' ";
    $query_link = mysqli_query($link,$query);
    if(mysqli_num_rows($query_link)>0){
        $row = mysqli_fetch_assoc($query_link);
        $goodWord = $row['replaceWord'];
        $element = $goodWord
    }
    $newComment = $newComment." ".$element; // append $element back to back to create modified comment
    }
   // now update the $newComment back to your comment Table
}