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
}
Related
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)) {
How to resolve this problem:
Write a PHP program that finds the word in a text.
The suffix is separated from the text by a pipe.
For example: suffix|SOME_TEXT;
input: text|lorem ips llfaa Loremipsumtext.
output: Loremipsumtext
My code is this, but logic maybe is wrong:
$mystring = fgets(STDIN);
$find = explode('|', $mystring);
$pos = strpos($find, $mystring);
if ($pos === false) {
echo "The string '$find' was not found in the string '$mystring'.";
}
else {
echo "The string '$find' was found in the string '$mystring',";
echo " and exists at position $pos.";
}
explode() returns an array, so you need to use $find[0] for the suffix, and $find[1] for the text. So it should be:
$suffix = $find[0];
$text = $find[1];
$pos = strpos($text, $suffix);
if ($pos === false) {
echo "The string '$suffix' was not found in '$text'.";
} else {
echo "The string '$suffix' was found in '$text', ";
echo " and exists at position $pos.";
}
However, this returns the position of the suffix, not the word containing it. It also doesn't check that the suffix is at the end of the word, it will find it anywhere in the word. If you want to match words rather than just strings, a regular expression would be a better method.
$suffix = $find[0];
$regexp = '/\b[a-z]*' . $suffix . '\b/i';
$text = $find[1];
$found = preg_match($regexp, $text, $match);
if ($found) {
echo echo "The suffix '$suffix' was found in '$text', ";
echo " and exists in the word '$match[0]'.";
} else {
echo "The suffix '$suffix' was not found in '$text'.";
}
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;
}
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.
Lets say the text file " data1.txt" contains:
56715||Jim||Green||19
5678||Sara||Red||92
53676||Mark||Orange||6
56787||Mike||Purple||123
56479||Sammy||Yellow||645
56580||Martha||Blue||952
ect...
.
.
I would like to echo only the line beginning with "5678||". "5678" is the exact $refVal or reference value. The line should display like this:
My name is: $nameVar
My color is: $colorVar
My number is: $numVar
Thanks...
$fh = fopen('data1.txt', 'r') or die('Unable to open data1.txt');
while($line = fgetcsv($fh, 0, '||')) {
if ($line[0] == 5678) {
echo <<<EOL
My name is: $line[1]
My color is $line[2]
My number is $line[3]
EOL;
break; // if there's only ever one '5678' line in the, get out now.
}
}
fclose($fh);
alternate version, as suggested by Jared below. Probably will be faster, as it only does the array creation on the line that actually matches, and not for each line as the fgetcsv version does.
$fh = fopen('data1.txt', 'r') or die('Unable to open data1.txt');
while($line = fgets($fh)) {
if (strpos($line, '5678||') === 0) { // only if right at start of string
$data = explode('||', $line);
echo <<<EOL
my name is blah blah blah
EOL;
break;
}
}
You can split each line into an array using explode, like so:
foreach ($lines as $line)
{
$t = explode('||', $line);
if ($t[0] == $refVal) {
// echo the rest of $t array however you want
// $t[1] would be the name, $t[2] the color, etc
}
}