0

我在使用 str_ireplace 和从数据库表返回的数组时遇到问题。我想用一张桌子来保存将从聊天中过滤掉的坏词。

$msg = "some user input, with a few bad words."; //(not putting bad words here, just an example)
$words = $this->db->query("SELECT * FROM tblBadWords")->result_array(); 
$replacement = "@#$@#";   
$msg = str_ireplace($words, $replacement, $msg);  //<--nothing happens

$word = str_ireplace($words[0], $replacement, $msg);  //<--nothing happens

$word = str_ireplace($words[1], $replacement, $msg);  //<--filters first word in table only

我究竟做错了什么?请注意,我是 php 数据库编码的新手。

4

2 回答 2

0

您需要深入研究您的阵列。目前,您的查询返回如下内容:

Array
    (
        [0] => Array
            (
                [ID] => 1
                [BadWord] => bad
            )
        [1] => Array
            (
                [ID] => 2
                [BadWord] => Input
            )
    )

这来自我假设一个表格的示例:

ID    |  BadWord
---------|-----------
1        | bad
2        | Input

您可以通过访问数组中的每个数组来实现挖掘,获取数组块(即 $badword[1] 其中 $badword[0] 是您的 ID 字段;我发现需要指定表格标题,因为这就是我的print_r 显示了数组)。

foreach($words as $badword){
        $replacethese = $badword['BadWord'];
        $msg = str_ireplace($replacethese, $replacement, $msg);
    }

现在你可以用 $msg 做任何事情了。我的出来是这样的:

some user @#$@#, with a few @#$@# words.
于 2013-11-02T05:07:11.180 回答
0

I guess, from that code, $words will be an array, each element representing one line of the SQL result. If you have a table like that:

    id |         badword
   ----|--------------------------
    1  |         kangaroo
    2  |         bad-kangaroo
    3  |         very-bad-kangaroo

There will be three lines in your PHP array. There are surely a lot of solutions to this, but as a simple solution, you could just iterate over the array like that:

foreach ($words as $lineInMyBadWordTable) {
    $msg = str_ireplace($lineInMyBadWordTable['badword'], $replacement, $msg);
}

So, basically, if you access $words[0] or $words[n], you'll access one row of the result set which has been returned by the database management system. $words[0] will most likely be a result as well, representing the complete row of the record. For further reference, please consult the PHP documentation of str_ireplace:

[http://php.net/manual/en/function.str-ireplace.php]

Hope that helps.

于 2013-11-02T04:42:56.157 回答