I made a text file named ben.txt and there are some numbers line by line, for example 123456 so i want, whenever someone type !check 123456 so they should get message like Number Banned
I Made a code But it doesn't working
My Code
$been = file_get_contents(ben.txt);
$isbanned = false;
foreach ($been as $bb) {
if(strpos($message, "!sa $bb") ===0) $isbanned = true;
sendMessage($chatId, "<b>Number Banned!</b>");
return;
}
You can turn the contents of the file into a regular expression that matches any of the strings.
$ex_cont = file("ben.txt", FILE_IGNORE_NEW_LINES);
$isbanned = false;
$regex = '/^!sa (' . implode('|', array_map('preg_quote', $ex_cont)) . ')/';
if (preg_match($regex, $message)) {
$isbanned = true;
sendMessage($chatId, "<b>Number Banned!</b>");
}
Related
I'm trying to develop a PHP application where it takes comments from users and then match the string to check if the comment is positive or negative. I have list of negative words in negative.txt file. If a word is matched from the word list, then I want a simple integer counter to increment by 1. I tried the some links and created the a code to check if the comment has is negative or positive but it is only matching the last word of the file.Here's the code what i have done.
<?php
function teststringforbadwords($comment)
{
$file="BadWords.txt";
$fopen = fopen($file, "r");
$fread = fread($fopen,filesize("$file"));
fclose($fopen);
$newline_ele = "\n";
$data_split = explode($newline_ele, $fread);
$new_tab = "\t";
$outoutArr = array();
//process uploaded file data and push in output array
foreach ($data_split as $string)
{
$row = explode($new_tab, $string);
if(isset($row['0']) && $row['0'] != ""){
$outoutArr[] = trim($row['0']," ");
}
}
//---------------------------------------------------------------
foreach($outoutArr as $word) {
if(stristr($comment,$word)){
return false;
}
}
return true;
}
if(isset($_REQUEST["submit"]))
{
$comments = $_REQUEST["comments"];
if (teststringforbadwords($comments))
{
echo 'string is clean';
}
else
{
echo 'string contains banned words';
}
}
?>
Link Tried : Check a string for bad words?
I added the strtolower function around both your $comments and your input from the file. That way if someone spells STUPID, instead of stupid, the code will still detect the bad word.
I also added trim to remove unnecessary and disruptive whitespace (like newline).
Finally, I changed the way how you check the words. I used a preg_match to split about all whitespace so we are checking only full words and don't accidentally ban incorrect strings.
<?php
function teststringforbadwords($comment)
{
$comment = strtolower($comment);
$file="BadWords.txt";
$fopen = fopen($file, "r");
$fread = strtolower(fread($fopen,filesize("$file")));
fclose($fopen);
$newline_ele = "\n";
$data_split = explode($newline_ele, $fread);
$new_tab = "\t";
$outoutArr = array();
//process uploaded file data and push in output array
foreach ($data_split as $bannedWord)
{
foreach (preg_split('/\s+/',$comment) as $commentWord) {
if (trim($bannedWord) === trim($commentWord)) {
return false;
}
}
}
return true;
}
1) Your storing $row['0'] only why not others index words. So problem is your ignoring some of word in text file.
Some suggestion
1) Insert the text in text file one by one i.e new line like this so you can access easily explode by newline to avoiding multiple explode and loop.
Example: sss.txt
...
bad
stupid
...
...
2) Apply trim and lowercase function to both comment and bad string.
Hope it will work as expected
function teststringforbadwords($comment)
{
$file="sss.txt";
$fopen = fopen($file, "r");
$fread = fread($fopen,filesize("$file"));
fclose($fopen);
foreach(explode("\n",$fread) as $word)
{
if(stristr(strtolower(trim($comment)),strtolower(trim($word))))
{
return false;
}
}
return true;
}
I am using this function to replace strings in a file:
function replace_in_file($FilePath, $OldText, $NewText)
{
$Result = array('status' => 'error', 'message' => '');
if(file_exists($FilePath)===TRUE)
{
if(is_writeable($FilePath))
{
try
{
$FileContent = file_get_contents($FilePath);
$FileContent = str_replace($OldText, $NewText, $FileContent);
if(file_put_contents($FilePath, $FileContent) > 0)
{
$Result["status"] = 'success';
}
else
{
$Result["message"] = 'Error while writing file';
}
}
catch(Exception $e)
{
$Result["message"] = 'Error : '.$e;
}
}
else
{
$Result["message"] = 'File '.$FilePath.' is not writable !';
}
}
else
{
$Result["message"] = 'File '.$FilePath.' does not exist !';
}
return $Result;
}
the problem is this: I have a lot of similar words in my file. so when I change one of them all of them changes. what should I do to change only that I want?
myfile.php:
define("word1","string");
define("word2","string");
define("word3","string");
...
(How to change for example string value in word1 without changing strings in others?)
There are a couple approaches you could take. Two I'll show here rely on the regular data structure you have indicated in your example file contents.
Rather than replacing the term "string" you could replace the term ("word1","string") keeping most of that substring the same but changing only the string portion.
Something like:
$fileContents = '
define("word1","string");
define("word2","string");
define("word3","string");
';
$oldText = '("word1","string")';
$newText = '("word1","NewString")';
$fileContents = str_replace($oldText,$newText,$fileContents);
echo $fileContents;
Another option is to search for "word1" or another search term, and replace a substring just after it (3 characters after it if your replacement term is separated from your search term by ",":
// File contents based on question text:
$fileContents = '
define("word1","string");
define("word2","string");
define("word3","string");
';
// Word to search for:
$searchWord = 'word1';
// Replacement text for that line:
$newText = "someNewText";
// to determine the length between the search term and the replacement term.
$seperator = '","';
// Get beginning position of the search string
if( $position = strpos($fileContents,$searchWord.$seperator) ) {
// Where the word to be replaced starts:
$start = $position + strlen($searchWord.$seperator);
// length of the term to be replaced:
$length = strlen("string");
// do the actual replacements:
$fileContents = substr_replace($fileContents,$newText,$start,$length);
}
echo $fileContents;
I've put both approaches into a php sandbox: approach 1, approach 2.
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.
Write PHP script to search for a word in a text file (titled a.txt). Text file contains 50 words, each word is on 1 line. On the JavaScript side, a client types a random word in a text field and submits the word. The PHP script searches through the 50 words to find the correct word using a loop that runs until the word is found in the a .txt file. If the word is not found, an error message must appear stating that the word was not in the list.
The JavaScript part is correct but I'm having trouble with PHP:
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
$a = trim($x);
if(strcmp($s, $a) == 0)
print("<h1>" . $_POST["lname"] . " is in the list</h1>");
else
print("<h1>" . $_POST["lname"] . " is not in the list</h1>");
fclose($file);
?>
If it's only 50 words then just make an array out of it and check if it's in the array.
$file = file_get_contents('a.txt');
$split = explode("\n", $file);
if(in_array($_POST["lname"], $split))
{
echo "It's here!";
}
function is_in_file($lname) {
$fp = #fopen($filename, 'r');
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
foreach ($array as $word) {
if ($word == $lname)
return True;
}
}
return False;
}
You are not searching the "word" into your code, but maybe the code below will help you
$array = explode("\n",$string_obtained_from_the_file);
foreach ($array as $value) {
if ($value== "WORD"){
//code to say it has ben founded
}
}
//code to say it hasn't been founded
here is something fancy, regular expression :)
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match('/^' . $s . '$/im', $x) === true){
// word found do what you want
}else{
// word not found, error
}
remove the i from '$/im' if you do not want to the search to be case-insensitive
the m in there tells the parser to match ^$ to line endings, so this works.
here is a working example : http://ideone.com/LmgksA
You actually don't need to break apart the file into an array if all you're looking for is a quick existence check.
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match("/\b".$s."\b/", $x)){
echo "word exists";
} else {
echo "word does not exists";
}
This matches any word token in a string.
I want to filter some reserved word on my title form.
$adtitle = sanitize($_POST['title']);
$ignore = array('sale','buy','rent');
if(in_array($adtitle, $ignore)) {
$_SESSION['ignore_error'] = '<strong>'.$adtitle.'</strong> cannot be use as your title';
header('Location:/submit/');
exit;
How to make something like this. If
user type Car for sale the sale
will detected as reserved keyword.
Now my current code only detect single keyword only.
You're probably looking for a regular expression:
foreach($ignore as $keyword) {
if(preg_match("/\b$keyword\b/i", $adtitle) {
// Uhoh, the user used a bad word!!
}
}
This will also prevent some false positives, such as 'torrent' not coming up as a reserved word because it contains 'rent'.
You could also try something like this:
$ignore = array('sale','rent','buy');
$invalid = array_intersect($ignore, preg_split('{\W+}', $adtitle));
Then $invalid will contain a list of all the reserved words used in the title. This could be useful if you wanted to explain why the title cannot be used.
EDIT:
$invalid = array_intersect($ignore, preg_split('{\W+}', strtolower($adtitle));
if you want case-insensitive matching.
$adtitle = sanitize($_POST['title']);
$ignoreArr =
array('sale','buy','rent');
foreach($ignoreArr as $ignore){
if(strpos($ignore, $adtitle)!==false){
$_SESSION['ignore_error'] = '<strong>'.$adtitle.'</strong> cannot
be use as your title';
break;
}
}
header('Location:/submit/');
exit;
This should work. Not tested though.
function isValidTitle($str) {
// these may want to be placed in a config file
$badWords = array('sale','buy','rent');
foreach($badWords as $word) {
if (strstr($str, $word)) return false; // found a word!
}
// no bad word found
return true;
}
If you'd like to match the words only (not partial matches as well, as in within other words), try this modified one below
function isValidTitle($str) {
$badWords = array('sale','buy','rent');
foreach($badWords as $word) {
if (preg_match('/\b' . trim($word) . '\b/i', $str)) return false;
}
return true;
}
How about something as simple as this:
if ( preg_match("/\b" . implode("|", $ignore) . "\b/i", $adtitle) ) {
// No good
}