How to count Array based on statement? - php

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

Your script also don't count extra the words if they are using the same word multiple times in a string. Below here is a script i should use.
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';
}

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';
}

Related

How to save multiple results in the array with for loop php

I'm working with a CSV file. when the user uploads the file. I parse the CSV then select the data from the array that I need. after that, I'm running a for loop to validate that data and saving the results in the array. but the problem is when I print the results array there's only result for 1 email and there are 4 emails. any suggestions?
$results = [];
$valid_emails = 0;
$invalid_emails = 0;
for ($i = 0; $i < $csv_array['row_count']; $i++) {
$email = $csv_array['data'][$i][$email_column];
$result = validate_email($email);
$results['Email'] = $email;
if ($result) {
$results['Result'] = 'valid';
$valid_emails++;
} else {
$results['Result'] = 'invalid';
$invalid_emails++;
}
}
echo '<pre>';
print_r($results);
echo '</pre><br>';
echo $valid_emails . '<br>';
echo $invalid_emails . '<br>';
Use $results[] to add one or more elements :
$results = [];
$valid_emails = 0;
$invalid_emails = 0;
for ($i = 0; $i < $csv_array['row_count']; $i++) {
$email = $csv_array['data'][$i][$email_column];
$result = validate_email($email);
$res['Email'] = $email;
if ($result) {
$res['Result'] = 'valid';
$valid_emails++;
} else {
$res['Result'] = 'invalid';
$invalid_emails++;
}
$results[] = $res;
}
echo '<pre>';
print_r($results);
echo '</pre><br>';
echo $valid_emails . '<br>';
echo $invalid_emails . '<br>';
You are overriding results every time in your loop, try this
$results = [];
$valid_emails = 0;
$invalid_emails = 0;
for ($i = 0; $i < $csv_array['row_count']; $i++) {
$email = $csv_array['data'][$i][$email_column];
$rowResult=[];
$result = validate_email($email);
$rowResult['Email'] = $email;
if ($result) {
$rowResult['Result'] = 'valid';
$valid_emails++;
} else {
$rowResult['Result'] = 'invalid';
$invalid_emails++;
}
$results[]=$rowResult;
}
echo '<pre>';
print_r($results);
echo '</pre><br>';
echo $valid_emails . '<br>';
echo $invalid_emails . '<br>';
$results contains only the last email validation.
You should store multiple results, and not only the last ;-)
Something like :
$results[$i]['Email'] = $email;
if ($result) {
$results[$i]['Result'] = 'valid';
$valid_emails++;
} else {
$results[$i]['Result'] = 'invalid';
$invalid_emails++;
}
if ($result) {
$results[$i] = 'valid';
$valid_emails++;
} else {
$results[$i] = 'invalid';
$invalid_emails++;
}

How to pass more arguments to that function?

I have this function:
function mobio_checkcode($servID, $code, $debug=0) {
$res_lines = file("http://www.mobio.bg/code/checkcode.php?servID=$servID&code=$code");
$ret = 0;
if($res_lines) {
if(strstr("PAYBG=OK", $res_lines[0])) {
$ret = 1;
}else{
if($debug)
echo $line."\n";
}
}else{
if($debug)
echo "Unable to connect to mobio.bg server.\n";
$ret = 0;
}
return $ret;
}
And here how i use it:
if(mobio_checkcode($servID, $code, 0) == 1) {
echo "Code is valid!!";
}
$code = $_REQUEST['code'];
$servID = 29;
$post = $_REQUEST['post'];
Here i have form! In this form u enter code and display is valid or no so i want to pass more $code like
$code1 = $_REQUEST['code1'];
$code2 = $_REQUEST['code2'];
$code3 = $_REQUEST['code3'];
I want to pass more variables to function how it will be done.. Please help me thank u <3
Just pass all of variables as array like
$array = ['servID'=>29,'code'=>XXXX];
function checkcode($array) {
//Do stuff
$array['servID']
$array['code']
}
function mobio_checkcode($servID, $code, $debug=0, $element1, $element2) {
$res_lines = file("http://www.mobio.bg/code/checkcode.php?servID=$servID&code=$code");
$ret = 0;
if($res_lines) {
if(strstr("PAYBG=OK", $res_lines[0])) {
$ret = 1;
}else{
if($debug)
echo $line."\n";
}
}else{
if($debug)
echo "Unable to connect to mobio.bg server.\n";
$ret = 0;
}
return $ret;
//you can pass extra elements so on.. otherwise create an array of elements and pass only array to function

How do I check if there are bad word in a string or not

This is my PHP code for replacing bad word in the string to *, it's working well.
But I want to check if in the string are bad word or not. How can I do this?
index.php
<?php
include("badwords.php");
$content = "cat bad_word dog";
$badword = new badword();
echo $badword->word_fliter("$content");
?>
badword.php
<?php
$bad_words = array (
// an array of bad words here...
);
class badword {
function word_fliter($content) {
global $bad_words, $wordreplace;
$count = count($bad_words);
for ($n = 0; $n < $count; ++$n, next ($bad_words)) {
$filter = "*";
//Search for bad_words in content
$search = "$bad_words[$n]";
$content = preg_replace("'$search'i","<i>$filter</i>",$content);
}
return $content;
}
}
?>
............................................................................................................................................................
edit: Since you wanted full code...
please note that i changed the function name from word_fliter() to word_filter()
index.php
<?php
include("badwords.php");
$content = "this is an example string with bad words in it";
$badword = new badword();
echo $badword->word_filter("$content");
if($badword->usedBadWords()){
// do whatever you want to do if bad words were used
}
?>
badwords.php
<?php
$bad_words = array (
// insert your naughty list here
);
class badword {
private $usedBadWords = false;
function word_filter($content) {
foreach($bad_words as $bad_word){
if(strpos($content, $bad_word) !== false){
$this->usedBadwords = true;
}
$content = str_replace($bad_word, '***', $content);
}
return $content;
}
function usedBadWords(){
return $this->usedBadWords;
}
}
?>
This should work, you just check if it the content matches any bad words and returns it.
index.php
<?php
include("badwords.php");
$content = "cat bad_word dog";
$badword = new badword();
$return_val = $badword->word_fliter("$content");
echo $return_val['content'];
if($return_val['has_bad_words']){
..do stuff
}
?>
badword.php
<?php
$bad_words = array (
// an array of bad words here...
);
class badword {
function word_fliter($content) {
global $bad_words, $wordreplace;
$count = count($bad_words);
$has_bad_words = false;
for ($n = 0; $n < $count; ++$n, next ($bad_words)) {
$filter = "*";
//Search for bad_words in content
$search = "$bad_words[$n]";
$content = preg_replace("'$search'i","<i>$filter</i>",$content);
if(preg_match("'$search'i", $content) && !$has_bad_words){
$has_bad_words = true;
}
else {
$has_bad_words = false;
}
}
return array('content' => $content, 'has_bad_words' => $has_bad_words);
}
}
<?php
$bad_words = array (
// an array of bad words here...
);
$bad_word_check = "";
$bad_word_detect = "";
class badword {
function word_fliter($content) {
global $bad_words, $wordreplace;
$count = count($bad_words);
for ($n = 0; $n < $count; ++$n, next ($bad_words)) {
$filter = "*";
//Search for bad_words in content
$search = "$bad_words[$n]";
$xx = "%".$search."%";
if(preg_match($xx, $content))
{
$bad_word_check = "1";
$bad_word_detect = $bad_word_detect."".$search.",";
}
$content = preg_replace("'$search'i","<i>$filter</i>",$content);
}
return array('content' => $content, 'bad_word_check' => $bad_word_check, 'bad_word_detect' => $bad_word_detect);
}
}
$content = "cat bad_word bad_word dog association";
$badword = new badword();
echo $badword->word_fliter("$content")[content];
echo "<BR>";
echo $badword->word_fliter("$content")[bad_word_check];
echo "<BR>";
echo $badword->word_fliter("$content")[bad_word_detect];
?>

Check if all the substring are included in a string using PHP

let's say I have 2 set of string to check.
$string = 12345;
$string2 = 15000;
//string must contain 1,2,3,4,5 to be returned true
if(preg_match('[1-5]',$string) {
return true;
} else {
return false;}
This code works for $string but not for $string2. It returns true too with $string2.
Please help!
If string must contain 1, 2, 3, 4 and 5, then you should use regex pattern
/^(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5).*/
which can be further optimize... for example:
/^(?=.*1)(?=.*2)(?=.*3)(?=.*4).*5/
If no other characters are allowed, then you should use regex pattern
/^(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)[1-5]*$/
You can check this with strpos as well:
<?php
function str_contains_all($string, $searchValues, $caseSensitive = false) {
if (!is_array($searchValues)) {
$searchValues = (string)$searchValues;
$searchValuesNew = array();
for ($i = 0; $i < strlen($searchValues); $i++) {
$searchValuesNew[] = $searchValues[$i];
}
$searchValues = $searchValuesNew;
}
$searchFunction = ($caseSensitive ? 'strpos' : 'stripos');
foreach ($searchValues as $searchValue) {
if ($searchFunction($string, (string)$searchValue) === false) {
return false;
}
}
return true;
}
?>
Use:
<?php
$string = 12345;
$string2 = 15000;
if (str_contains_all($string, 12345)) {
echo 'Y';
if (str_contains_all($string2, 12345)) {
echo 'Y';
} else {
echo 'N';
}
} else {
echo 'N';
}
?>
Which outputs:
YN
DEMO

bad words filter integration

I am trying to integrate php bad words filter
The input is taken through $_REQUEST['qtitle'] and $_REQUEST['question']
But I am failed to do so
$USERID = intval($_SESSION['USERID']);
if ($USERID > 0)
{
$sess_ver = intval($_SESSION[VERIFIED]);
$verify_asker = intval($config['verify_asker']);
if($verify_asker == "1" && $sess_ver == "0")
{
$error = $lang['225'];
$theme = "error.tpl";
}
else
{
$theme = "ask.tpl";
STemplate::assign('qtitle',htmlentities(strip_tags($_REQUEST['qtitle']), ENT_COMPAT, "UTF-8"));
STemplate::assign('question',htmlentities(strip_tags($_REQUEST['question']), ENT_COMPAT, "UTF-8"));
if($_REQUEST['subform'] != "")
{
$qtitle = htmlentities(strip_tags($_REQUEST['qtitle']), ENT_COMPAT, "UTF-8");
$question = htmlentities(strip_tags($_REQUEST['question']), ENT_COMPAT, "UTF-8");
$category = intval($_REQUEST['category']);
if($qtitle == "")
{
$error = $lang['3'];
}
elseif($category <= "0")
{
$error = $lang['4'];
}
else
{
if($config['approve_stories'] == "1")
{
$addtosql = ", active='0'";
}
$query="INSERT INTO posts SET USERID='".mysql_real_escape_string($USERID)."', title='".mysql_real_escape_string($qtitle)."',question='".mysql_real_escape_string($question)."', tags='".mysql_real_escape_string($qtitle)."', category='".mysql_real_escape_string($category)."', time_added='".time()."', date_added='".date("Y-m-d")."' $addtosql";
$result=$conn->execute($query);
$userid = mysql_insert_id();
$message = $lang['5'];
}
}
}
}
else
{
$question = htmlentities(strip_tags($_REQUEST['qtitle']), ENT_COMPAT, "UTF-8");
$redirect = base64_encode($thebaseurl."/ask?qtitle=".$question);
header("Location:$config[baseurl]/login?redirect=$redirect");exit;
}
I am trying the following code but this code replaces every word (which is not included in the array)
FUNCTION BadWordFilter(&$text, $replace){
$bads = ARRAY (
ARRAY("butt","b***"),
ARRAY("poop","p***"),
ARRAY("crap","c***")
);
IF($replace==1) { //we are replacing
$remember = $text;
FOR($i=0;$i<sizeof($bads);$i++) { //go through each bad word
$text = EREGI_REPLACE($bads[$i][0],$bads[$i][1],$text); //replace it
}
IF($remember!=$text) RETURN 1; //if there are any changes, return 1
} ELSE { //we are just checking
FOR($i=0;$i<sizeof($bads);$i++) { //go through each bad word
IF(EREGI($bads[$i][0],$text)) RETURN 1; //if we find any, return 1
}
}
}
$qtitle = BadWordFilter($wordsToFilter,0);
$qtitle = BadWordFilter($wordsToFilter,1);
What I am missing here?
I agree with #Gordon that this is reinventing the wheel, but if you really want to do it, here's a better start:
function badWordFilter(&$text, $replace)
{
$patterns = array(
'/butt/i',
'/poop/i',
'/crap/i'
);
$replaces = array(
'b***',
'p***',
'c***'
);
$count = 0;
if($replace){
$text = preg_replace($patterns, $replaces, $text, -1, $count);
} else {
foreach($patterns as $pattern){
$count = preg_match($pattern, $text);
if($count > 0){
break;
}
}
}
return $count;
}
There are lots of inherent issues, though. For instance, run the filter on the text How do you like my buttons? ... You'll end up with How do you like my b***ons?
I think you should use this kind of function :
function badWordsFilter(&$text){
$excluded_words = array( 'butt', 'poop', 'crap' );
$replacements = array();
$i = count($excluded_words);
while($i--){
$tmp = $excluded_words{0};
for($i=0;$i<(strlen($excluded_words)-1);$i++){
$tmp .= '*';
}
$replacements[] = $tmp;
}
str_replace($excluded_words, $replacements, $text);
}

Categories