Tatif Isu Tatif Isu - 5 months ago 9
HTML Question

How to count Array based on statement?

I use validate php function to filter badword. And my problem is this script can't count badword in a statement that I've input. How to count badword in a statement..?

For example: You're badword1 and they badword2.

It's supposed to be 2 badword in that sentence.

PHP

function validasi($string,$banned_words) {
foreach($banned_words as $banned_word) {
if(stristr($string,$banned_word)){
return false;
}
}
return true;
}
$banned_words = array('badword1','badword2','badword3','badword4','badword5','badword6','badword7');
$teks = $_POST['teks'];
if (!validasi($teks,$banned_words)) {
echo count(!validasi($teks,$banned_words));
echo 'blocked!';
}else{
echo 'Text valid';
}


HTML

<form action="validasi.php" method="POST">
<input type="text" name="teks">
<input type="submit" value="Validasi">
</form>


Output


1 !blocked.


Expected Result


2 !blocked

Answer

do this

function validasi($string,$banned_words) {
$badWordCount = 0;
foreach($banned_words as $banned_word) {
if(stristr($string,$banned_word)){
$badWordCount++;
}
}
return $badWordCount;
}
$banned_words = array('badword1','badword2','badword3','badword4','badword5','badword6','badword7');
$teks = $_POST['teks'];
$badWordsCount2 = validasi($teks,$banned_words);
if ($badWordsCount2 != 0) {
echo $badWordsCount2;
echo 'blocked!';
}else{
echo 'Text valid';
}
Comments