Ofri
Ofri

Reputation: 51

PHP Badword Filtering parse by Space

i have function for badword, this function work : like this

<form action="bad.php" method="post" />
<br />
<br />
Your Word
<input type="text" placeholder="Your Word" name="in" />
<br />
<br />
<textarea name="bad" cols="20" rows="10">sex</textarea> *) parse by enter
<br />
<br />
<input type="submit" value="cek" name="cek" />
</form>
<?php


if(isset($_POST['cek'])){


function badWordFilter($data)
    {     
        $bad= preg_split('/\r\n|[\r\n]/', $_POST['bad']);
        $originals          = (array_filter($bad));
        $replacements       = "";
        $data               = str_ireplace($originals,$replacements,$data);
        return $data;
    }   


echo "<br />";
echo "Input : ".$_POST['in'];   

echo "<br />";
echo "OutPut : ".badWordFilter($_POST['in']);           
}
?>

The Output showing this :

in : foto sex with sexygirl
out : foto with girl

but i want the output like this :

in : foto sex with sexygirl
out : foto with sexygirl

badword only remove stay alone word ?

Upvotes: 1

Views: 103

Answers (2)

Ihor Burlachenko
Ihor Burlachenko

Reputation: 4905

The following code does the job:

function badWordFilter($data)
{
    $bad = preg_split('/\r\n|[\r\n]/', $_POST['bad']);
    $originals = array_map('strtolower', array_filter($bad));;

    $words = array_map('trim', explode(' ', $data));
    $filtered = array_filter($words, function($v) use ($originals) { 
        return !in_array(strtolower($v), $originals); 
    });

    return implode(' ', $filtered);
}

It splits the string into words, filters out bad words and builds new filtered string.

Upvotes: 0

Manikiran
Manikiran

Reputation: 1

Try the following code:

function wordFilter($text)
{
    $filter_terms = array('\bass(es|holes?)?\b', '\bshit(e|ted|ting|ty|head)\b');
    $filtered_text = $text;
    foreach($filter_terms as $word)
    {
    $match_count = preg_match_all('/' . $word . '/i', $text, $matches);
    for($i = 0; $i < $match_count; $i++)
        {
        $bwstr = trim($matches[0][$i]);
        $filtered_text = preg_replace('/\b' . $bwstr . '\b/', str_repeat("*", strlen($bwstr)), $filtered_text);
        }
    }
    return $filtered_text;
}

You can easily add words into the $filter_terms array; note that the beginning / and trailing /i are automatically included in the loop, eliminating the need to type them every time. You can also add "greedy" matches; simply remove the \b from both ends of the word, and the filter will catch anything that contains that word within it. A good idea would be to load all of the terms into the array from an external file.

Upvotes: 2

Related Questions