Lets say I have an array of bad words:
$badwords = array("one", "two", "three");
And random string:
$string = "some variable text";
How to create this cycle:
if (one or more items from the $badwords array is found in $string)
echo "sorry bad word found";
else
echo "string contains no bad words";
Example:
if $string = "one fine day" or "one fine day two of us did something", user should see sorry bad word found message.
If $string = "fine day", user should see string contains no bad words message.
As I know, you can't preg_match from array. Any advices?
How about this:
$badWords = array('one', 'two', 'three');
$stringToCheck = 'some stringy thing';
// $stringToCheck = 'one stringy thing';
$noBadWordsFound = true;
foreach ($badWords as $badWord) {
if (preg_match("/\b$badWord\b/", $stringToCheck)) {
$noBadWordsFound = false;
break;
}
}
if ($noBadWordsFound) { ... } else { ... }
Why do you want to use preg_match() here?
What about this:
foreach($badwords as $badword)
{
if (strpos($string, $badword) !== false)
echo "sorry bad word found";
else
echo "string contains no bad words";
}
If you need preg_match() for some reasons, you can generate regex pattern dynamically. Something like this:
$pattern = '/(' . implode('|', $badwords) . ')/'; // $pattern = /(one|two|three)/
$result = preg_match($pattern, $string);
HTH
If you want to check each word by exploding the string into words, you can use this:
$badwordsfound = count(array_filter(
explode(" ",$string),
function ($element) use ($badwords) {
if(in_array($element,$badwords))
return true;
}
})) > 0;
if($badwordsfound){
echo "Bad words found";
}else{
echo "String clean";
}
Now, something better came to my mind, how about replacing all the bad words from the array and check if the string stays the same?
$badwords_replace = array_fill(0,count($badwords),"");
$string_clean = str_replace($badwords,$badwords_replace,$string);
if($string_clean == $string) {
echo "no bad words found";
}else{
echo "bad words found";
}
Here is the bad word filter I use and it works great:
private static $bad_name = array("word1", "word2", "word3");
// This will check for exact words only. so "ass" will be found and flagged
// but not "classic"
$badFound = preg_match("/\b(" . implode(self::$bad_name,"|") . ")\b/i", $name_in);
Then I have another variable with select strings to match:
// This will match "ass" as well as "classic" and flag it
private static $forbidden_name = array("word1", "word2", "word3");
$forbiddenFound = preg_match("/(" . implode(self::$forbidden_name,"|") . ")/i", $name_in);
Then I run an if on it:
if ($badFound) {
return FALSE;
} elseif ($forbiddenFound) {
return FALSE;
} else {
return TRUE;
}
Hope this helps. Ask if you need me to clarify anything.
Related
I already have a code:
<?
$eventname = $event->title;
$bad_words = array('Example1','Example2','Example3','Example4','Example5','Example6');
foreach($bad_words as $bad_word){
if(strpos($eventname, $bad_word) !== false) {
echo '';
break;
}
else {
echo '<div class="uk-text-contrast">'.translate('HIDDEN_INFO_DATE').'</div>';
break;
}
}
?>
this works, but only if the $eventname contains example1. But I want to hide echo '<div class="uk-text-contrast">'.translate('HIDDEN_INFO_DATE').'</div>'; from all of the defined words in the $bad_words.
How can I hide the echo if there is one of the $bad_words?
Why don't you use the in_array function? It's even shorter in that way.
if (in_array($eventname, $bad_words)) {
echo '';
} else {
echo '<div>';
}
remobe 'break' from code
foreach($bad_words as $bad_word){
if(strpos($eventname, $bad_word) !== false) {
echo '';
}
else {
echo '<div class="uk-text-contrast">'.translate('HIDDEN_INFO_DATE').'</div>';
}
}
I would convert the string $eventname to an array and then use the array Intersect function
$eventname = "sgswfdg Example1 sdfh dh dfa hadhadh";
$title_to_array=explode(" ", $eventname);
$bad_words = array('Example1','Example2','Example3','Example4','Example5','Example6');
$result = !empty(array_intersect($bad_words , $title_to_array ));
if ($result){
echo '';
} else {
echo $eventname;
}
Rather than using a loop, you could split the title into it's separate words and then check if there are any words in the $bad_words list using array_intersect()
// $eventname = $event->title;
$eventname = 'Some text';
$eventname = 'Some text Example1';
$bad_words = array('Example1','Example2','Example3','Example4','Example5','Example6');
$eventWords = explode(" ", $eventname);
if ( empty (array_intersect($eventWords, $bad_words))) {
// Event name is OK
echo $eventname;
}
This has some examples to show how it works.
Note that this code doesn't pick up things like Example1234 which strpos() would.
Update:
Just to make it more flexible, you can use regular expressions in case you have punctuation in the title...
$eventname = 'Some text';
$eventname = 'Some text,Example1';
$bad_words = array('Example1','Example2','Example3','Example4','Example5','Example6');
preg_match_all('/(\w+)/', $eventname, $eventWords);
if ( empty (array_intersect($eventWords[1], $bad_words))) {
echo '<div class="uk-text-contrast">'.translate('HIDDEN_INFO_DATE').'</div>';
}
( Note: Regular expressions aren't my subject so please let me know if this needs to be improved).
This function filer the email from text and return matched pattern
function parse($text, $words)
{
$resultSet = array();
foreach ($words as $word){
$pattern = 'regex to match emails';
preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE );
$this->pushToResultSet($matches);
}
return $resultSet;
}
Similar way I want to match bad words from text and return them as $resultSet.
Here is code to filter badwords
TEST HERE
$badwords = array('shit', 'fuck'); // Here we can use all bad words from database
$text = 'Man, I shot this f*ck, sh/t! fucking fu*ker sh!t f*cking sh\t ;)';
echo "filtered words <br>";
echo $text."<br/>";
$words = explode(' ', $text);
foreach ($words as $word)
{
$bad= false;
foreach ($badwords as $badword)
{
if (strlen($word) >= strlen($badword))
{
$wordOk = false;
for ($i = 0; $i < strlen($badword); $i++)
{
if ($badword[$i] !== $word[$i] && ctype_alpha($word[$i]))
{
$wordOk = true;
break;
}
}
if (!$wordOk)
{
$bad= true;
break;
}
}
}
echo $bad ? 'beep ' : ($word . ' '); // Here $bad words can be returned and replace with *.
}
Which replaces badwords with beep
But I want to push matched bad words to $this->pushToResultSet() and returning as in first code of email filtering.
can I do this with my bad filtering code?
Roughly converting David Atchley's answer to PHP, does this work as you want it to?
$blocked = array('fuck','shit','damn','hell','ass');
$text = 'Man, I shot this f*ck, damn sh/t! fucking fu*ker sh!t f*cking sh\t ;)';
$matched = preg_match_all("/(".implode('|', $blocked).")/i", $text, $matches);
$filter = preg_replace("/(".implode('|', $blocked).")/i", 'beep', $text);
var_dump($filter);
var_dump($matches);
JSFiddle for working example.
Yes, you can match bad words (saving for later), replace them in the text and build the regex dynamically based on an array of bad words you're trying to filter (you might store it in DB, load from JSON, etc.). Here's the main portion of the working example:
var blocked = ['fuck','shit','damn','hell','ass'],
matchBlocked = new RegExp("("+blocked.join('|')+")", 'gi'),
text = $('.unfiltered').text(),
matched = text.match(matchBlocked),
filtered = text.replace(matchBlocked, 'beep');
Please see the JSFiddle link above for the full working example.
When i search for "bank", it should display Bank-List1, Bank-List2 from the following list.
Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1.
Is there is any php function to display?
I got the output for exact match. But no result for this type of search.
Please help me to find the solution.
you can use stristr
stristr — Case-insensitive strstr()
<?php // Example from PHP.net
$string = 'Hello World!';
if(stristr($string, 'earth') === FALSE) {
echo '"earth" not found in string';
}
// outputs: "earth" not found in string
?>
So for your situation, if your list was in an array named $values
you could do
foreach($values as $value)
{
if(stristr($value, 'bank') !== FALSE)
{
echo $value."<br>";
}
}
You can do it using stristr. This function returns all of haystack starting from and including the first occurrence of needle to the end. Returns the matched sub-string. If needle is not found, returns FALSE.
Here is the complete code:
<?php
$str="Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1";
$findme="bank";
$tokens= explode(",", $str);
for($i=0;$i<count($tokens);$i++)
{
$trimmed =trim($tokens[$i]);
$pos = stristr($trimmed, $findme);
if ($pos === false) {}
else
{
echo $trimmed.",";
}
}
?>
DEMO
This solution is only valid for this pattern of text is like: word1, word2, word3
<?php
$text = 'Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1.';
function search_in_text($word, $text){
$parts = explode(", ", $text);
$result = array();
$word = strtolower($word);
foreach($parts as $v){
if(strpos(strtolower($v), $word) !== false){
$result[] = $v;
}
}
if(!empty($result)){
return implode(", ", $result);
}else{
return "not found";
}
}
echo search_in_text("bank", $text);
echo search_in_text("none", $text);
?>
output:
Bank-List1, Bank-List2
not found
Lets say I have an array of bad words:
$badwords = array("one", "two", "three");
And random string:
$string = "some variable text";
How to create this cycle:
if (one or more items from the $badwords array is found in $string)
echo "sorry bad word found";
else
echo "string contains no bad words";
Example:
if $string = "one fine day" or "one fine day two of us did something", user should see sorry bad word found message.
If $string = "fine day", user should see string contains no bad words message.
As I know, you can't preg_match from array. Any advices?
How about this:
$badWords = array('one', 'two', 'three');
$stringToCheck = 'some stringy thing';
// $stringToCheck = 'one stringy thing';
$noBadWordsFound = true;
foreach ($badWords as $badWord) {
if (preg_match("/\b$badWord\b/", $stringToCheck)) {
$noBadWordsFound = false;
break;
}
}
if ($noBadWordsFound) { ... } else { ... }
Why do you want to use preg_match() here?
What about this:
foreach($badwords as $badword)
{
if (strpos($string, $badword) !== false)
echo "sorry bad word found";
else
echo "string contains no bad words";
}
If you need preg_match() for some reasons, you can generate regex pattern dynamically. Something like this:
$pattern = '/(' . implode('|', $badwords) . ')/'; // $pattern = /(one|two|three)/
$result = preg_match($pattern, $string);
HTH
If you want to check each word by exploding the string into words, you can use this:
$badwordsfound = count(array_filter(
explode(" ",$string),
function ($element) use ($badwords) {
if(in_array($element,$badwords))
return true;
}
})) > 0;
if($badwordsfound){
echo "Bad words found";
}else{
echo "String clean";
}
Now, something better came to my mind, how about replacing all the bad words from the array and check if the string stays the same?
$badwords_replace = array_fill(0,count($badwords),"");
$string_clean = str_replace($badwords,$badwords_replace,$string);
if($string_clean == $string) {
echo "no bad words found";
}else{
echo "bad words found";
}
Here is the bad word filter I use and it works great:
private static $bad_name = array("word1", "word2", "word3");
// This will check for exact words only. so "ass" will be found and flagged
// but not "classic"
$badFound = preg_match("/\b(" . implode(self::$bad_name,"|") . ")\b/i", $name_in);
Then I have another variable with select strings to match:
// This will match "ass" as well as "classic" and flag it
private static $forbidden_name = array("word1", "word2", "word3");
$forbiddenFound = preg_match("/(" . implode(self::$forbidden_name,"|") . ")/i", $name_in);
Then I run an if on it:
if ($badFound) {
return FALSE;
} elseif ($forbiddenFound) {
return FALSE;
} else {
return TRUE;
}
Hope this helps. Ask if you need me to clarify anything.
Is there any way to tell if a preg_replace was successful or not?
I tried:
<?php
$stringz = "Dan likes to eat pears and his favorite color is green and green!";
$patterns = array("/pears/","/green/", "/red/");
if ($string = preg_replace($patterns, '<b>\\0</b>', $stringz, 1)) {
echo "<textarea rows='30' cols='100'>$string</textarea>";
}else{
echo "Nope. You didn't have all the required patterns in the array.";
}
?>
and yes, I looked at php docs for this one. Sorry about my stupid questions earlier.
You can use the last param of preg_replace: &$count, which will contain the number of replacements that were done:
$stringz = "Dan likes to eat pears and his favorite color is green and green!";
$patterns = array("/pears/","/green/","/green/");
$new_patterns = array();
foreach ($patterns as $p)
if (array_key_exists($p, $new_patterns))
$new_patterns[$p]++;
else
$new_patterns[$p] = 1;
$string = $stringz;
$success = TRUE;
foreach ($new_patterns as $p => $limit)
{
$string = preg_replace($p, '<b>\\0</b>', $string, $limit, $count);
if (!$count)
{
$success = FALSE;
break;
}
}
if ($success)
echo "<textarea rows='30' cols='100'>$string</textarea>";
else
echo "Nope. You didn't have all the required patterns in the array.";
edited to fix the issue when there are two of the same in $patterns
if (preg_replace($patterns, '<b>$0</b>', $stringz, 1) != $stringz)
echo 'preg_replace was successful'
From the documentation:
If matches are found, the new subject
will be returned, otherwise subject
will be returned unchanged or NULL if
an error occurred.
So:
$string = preg_replace($patterns, '<b>\\0</b>', $stringz, 1);
if($string != $stringz) {
// something was replaced
}