I am doing something wrong?
This doesn't take any effects
$id = $_POST['id'];
$tudof = "\n #QTP ".$qtp." ID: ".$id;
echo "\n";
$fp = fopen('../../../ids.txt', 'a+');
$searchString = "id";
if(exec('grep '.escapeshellarg($searchString).' '.$fp)) {
break;
} else {
// Add the new name
fwrite($fp, $writef);
fclose($fp);
}
How to search a string and if not found add a new name?
I believe this will work.
I use file_get_contents to load the file as one string and use strpos to find "id".
I also include a preg_match version since strpos will match "lid" for "id" which preg_match won't.
$id = $_POST['id'];
$tudof = "\n #QTP ".$qtp." ID: ".$id;
echo "\n";
$str = file_get_contents('../../../ids.txt');
$searchString = "id";
if(strpos($str, $searchString) !==false) {
// Found it! Break won't work.
// If you want to stop all php code use exit;
} else {
// Add the new name
// Not sure what you do here but use file_put_contents
file_put_contents('../../../ids.txt', $str);
}
// Preg_match
if(preg_match("/\b " . $str ."\b/", $searchString)) {
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.
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 think i was doing halfway good to get this to halfway work. Anyways the following code works to find it on the first line, but i have a script that creates each on an individual line.
Please revise or create a completely new version of the following to make it to search for the form data on every line.
$search = $_POST['search'];
$file = file("SLIST.txt");
foreach($file as $line)
{
$line = trim($line);
if($line == $search)
{
echo $search . " WAS found in the database";
}
else
{
echo $search . " was NOT found in the database";
}
}
by form i mean there is a search form on the previous page. This page is the page where it tells you whether the text put into the search form matches a line in the file (ex: Line 1: BOOT Line 2: Tree Search entry: Tree Echo msg: Tree WAS found in the database.)
It is currently not working like i intended.
If you only want to know if the search string was in the file, and don't care on which line, then strpos() (doc) with file_get_contents() might be for you like this:
$file = file_get_contents('SLIST.txt');
$search = $_POST['search'];
if (strpos($file,$search)){
echo $search . " WAS found in the database";
}
else
{
echo $search . " was NOT found in the database";
}
If you want to know the line, your solutions should work as well if you change the if($line == $search) with my strpos().
If the line has to be exactly the search query you are looking for, then your solution should work just fine
It isn't so clear. I suppose the following is what you wanted.
<?php
$search = $_POST['search'];
$file = file("SLIST.txt");
$found = false;
foreach($file as $line) {
$line = trim($line);
if($line == $search) {
$found = true;
break;
}
}
if ($found)
{
echo $search . " WAS found in the database";
}
else {
echo $search . " was NOT found in the database";
}
?>
Are you looking to find a single string in an entire file. i know you want to look on every line but this is more efficient.
Try this
$file = file_get_contents("SLIST.txt");
if(strpos($file, $search))
{
echo $search . " WAS found in the database";
}
else {
echo $search . " was NOT found in the database";
}
If you just want to read lines then do
if(strpos($line, $search))
{
echo "found";
}
else
{
echo "not found";
}
I use the following code to search the text file:
$query="red";
$FileName = "search.txt";
$fh = fopen($FileName, 'r') or die("Can't open file");
$data = fread($fh, filesize($FileName));
$Pos = strpos($data,$query);
if ($Pos)
{
echo "Found";
}
else
{
echo "Not Found";
}
Let the text file be:
orange_red blue_gray yellow_blue white_black
It finds red at orange_red,but i want to match the whole word.
For example:
If the text to be searched is to be red
I want it to return false because red does not exist independently it is part of word orange_red.
In brief i want to search words delimited by space
Searching red and orange should return false and searching orange_red should return true.
Split the string into an array using explode. Then search the array using array_search to see if it contains your exact word.
This is the easiest/fastest way I can think of:
$query = "red";
$FileName = "search.txt";
if(preg_match("/\b" . $query . "\b/i"), file_get_contents($FileName))
{
echo "Found";
}
else
{
echo "Not Found";
}
\b matches a word boundary, so it will only return stand-alone results for $query. preg_match returns an int denoting the number of times the pattern was found (which will be either 0 or 1, as preg_match stops after the first match - use preg_match_all to get an accurate count of how many times the pattern appears in the target).
$query="red";
$FileName = "search.txt";
foreach (explode(" ", strtolower(file_get_contents($FileName)) as $word) {
if (strtolower($query) == $word) {
$found = true;
break;
}
}
echo $found ? "Found" : "Not found";
Meh, a little less efficient, but it gets the job done.
Try this, splits the data at a space, and then sees if the query is in the array.
$query="red";
$FileName = "search.txt";
$fh = fopen($FileName, 'r') or die("Can't open file");
$data = fread($fh, filesize($FileName));
$items = explode(" ", $data);
$Pos = array_search ($query, $items);
if($Pos !== FALSE)
{
echo "Found";
}
else
{
echo "Not Found";
}
Try using strpos with " $query ", or use a regular expression and preg_match:
$query = "red";
if (strpos($data, " {$query} ") !== false) {
// data contains " red "
}
// OR
if (preg_match("/(^{$query}( )|( ){$query}( )|( ){$query}$)/", $data) === 1) {
// match found
}