Php 如何根据语句对数组进行计数?
我使用验证php函数来过滤坏词。我的问题是这个脚本不能计算我输入的语句中的坏单词。如何计算语句中的坏话 例如:你是坏人,他们是坏人。Php 如何根据语句对数组进行计数?,php,html,arrays,Php,Html,Arrays,我使用验证php函数来过滤坏词。我的问题是这个脚本不能计算我输入的语句中的坏单词。如何计算语句中的坏话 例如:你是坏人,他们是坏人。 那句话应该是两个坏话 PHP function validasi($string,$banned_words) { foreach($banned_words as $banned_word) { if(stristr($string,$banned_word)){ return false; }
那句话应该是两个坏话 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>
输出
一!!封锁
预期结果
二!!封锁
这样做
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';
}
如果您的脚本在一个字符串中多次使用同一个单词,则不会计算额外的单词。下面是我应该使用的脚本
function getBadWords(){
$db_con = new PDO('dsn', 'use', 'pass'); // You PDO connection
$query = $db_con->prepare("SELECT * FROm tb_bannedwords");
$query->execute();
$return = array();
while($row=$query->fetch(PDO::FETCH_OBJ)) {
$data = $return[] = $row->banned_words;
}
return $return;
}
function validate($string){
$banned_words = getBadWords();
$count = 0;
foreach($banned_words as $banned_word){
$wordCount = substr_count($string, $banned_word);
if($wordCount > 0){
$count = $count + $wordCount;
}
}
return $count;
}
$teks = 'You\'re badword1 and they badword2 with badword1';
if(validate($teks) > 0){
echo validate($teks) . ' blocked!';
}else{
echo 'Text valid';
}
!validasi($teks,$banked_words)
为true
或false
:如果参数不是数组或不是具有实现接口的对象,则将返回1。validasi函数仅返回布尔值(真/假),而“真”布尔值在PHP中打印为“1”。您将需要跟踪该函数中的计数数,然后打印该计数。如果输入为“badword1和badword1”,结果是1
还是2
?感谢您的评论。可能是重复的谢谢。。。但是我有个问题。。如果我从数据库中获取数据,如何将其更改为数组<代码>$query=$db\u con->prepare(“从tb\u bannedwords中选择*)$查询->执行()$return=array();而($row=$query->fetch(PDO::fetch_OBJ)){$data=$return[]=$row->banked_words;}$count=0;foreach($count=substr\U count($string,$count>0){$count=$count+$wordCount;}}}返回$count;}代码>