I have a text file that maintains a list of words.
What I am trying to do is pass a string(sentence) to this function and remove the word from the string if it exists in the text file.
<?php
error_reporting(0);
$str1= "the engine has two ways to run: batch or conversational. In batch, expert system has all the necessary data to process from the beginning";
common_words($str1);
function common_words($string) {
$file = fopen("common.txt", "r") or exit("Unable to open file!");
$common = array();
while(!feof($file)) {
array_push($common,fgets($file));
}
fclose($file);
$words = explode(" ",$string);
print_r($words);
for($i=0; $i <= count($words); $i+=1) {
for($j=0; $j <= count($common); $j+=1) {
if($words[$i] == $common[$j]){
unset($words[$i]);
}
}
}
}
?>
It doesn't seem to work however. The common words from the string are not being removed. instead I am getting the same string with the one I started.
I think I am doing the loop wrong. What is the correct approach and what am I doing wrong?
on the line
if($words[$i] == $common[$j]){
change it to
if(in_array($words[$i],$common)){
and remove the second for loop.
Try using str_replace():
foreach($common as $cword){
str_replace($cwrod, '', $string); //replace word with empty string
}
Or in full:
<?php
error_reporting(0);
$str1= "the engine has two ways to run: batch or conversational. In batch, expert system has all the necessary data to process from the beginning";
common_words($str1);
function common_words(&$string) { //changes the actual string passed with &
$file = fopen("common.txt", "r") or exit("Unable to open file!");
$common = array();
while(!feof($file)) {
array_push($common,fgets($file));
}
fclose($file);
foreach($common as $cword){
str_replace($cword, '', $string); //replace word with empty string
}
}
?>
Related
The numbers in my file are 5X5:
13456
23789
14789
09678
45678
I'm trying to put it into this form
array[0]{13456}
array[1]{23789}
array[2]{14789}
array[3]{09678}
array[4]{45678}
My code is:
$fileName = $_FILES['file']['tmp_name'];
//Throw an error message if the file could not be open
$file = fopen($fileName,"r") or exit("Unable to open file!");
while ($line = fgets($file)) {
$digits .= trim($line);
$members = explode("\n", str_replace(array("\r\n","\n\r","\r"),"\n",$digits));
echo $members;
The output I'm getting is this:
ArrayArrayArrayArrayArray
fgets gets a line from the file pointer, so theoretically there should be no "\r" or "\n" characters in $line. explode will still work, even if the delimiter is not found. You'll just end up with an array with one item, the entire string. You can't echo an array, though. (That's why you're seeing Array for each line; it's the best PHP can do when you use echo on an array.)
If I were you, I would rather just use file() instead.
$members = array_map('trim', file($fileName, FILE_IGNORE_NEW_LINES));
With the example file you showed, this should result in
$members = ['13456', '23789', '14789', '09678', '45678'];
You can simply put the lines into an array and use print_r instead of echo to print that array
while ($line = fgets($file)) {
$members[] = $line;
}
print_r($members);
It should depend on the file that you are dealing with.
FileType:
text -> fgets($file)
CSV -> fgetcsv($file)
This question already has answers here:
RegEx to remove /** */ and // ** **// php comments
(3 answers)
Closed 4 years ago.
I need to delete a particular file content that is between these two characters /* & */ using PHP. The file from which I am trying to remove these comments is very large and includes a large data set, So optimized solution will be appreciated.
Example content:
/*SOME TEXT HERE
*/ 12314
So, the final file should contain only
1234
Here is the method that keeps on running until we got the comments string. Please note that the comments are only at one place in the file and they are always on the top of the file. Please let me know how can I delete those lines on which match the comments condition?
Below is the method that I updated.
$reading = fopen(public_path('file.csv'), 'r');
$writing = fopen(public_path('file.csv'), 'w');
$counter = 0;
$line = "";
$no_of_lines = 0;
while (!feof($reading) && $counter != 2) {
$new_line = fgets($reading);
if ($matched_string = strstr($new_line, "/*")) {
$line = $line . $matched_string;
$counter++;
} elseif ($matched_string = strstr($new_line, "*/")) {
$line = $line . $matched_string;
$counter++;
} else {
$line = $line . $new_line;
fwrite($writing, "");
}
$no_of_lines++;
}
fclose($writing);
fclose($reading);
First open the file but one line at a time to save memory:
<?php
$reading = fopen('myfile', 'r');
$writing = fopen('newfile', 'w');
while (!feof($reading)) {
$line = fgets($reading);
// We will put the removal logic in here
fputs($writing, $line);
}
fclose($reading);
fclose($writing);
For the removal, use some regex.
<?php
$line = preg_replace('#\/\*.+\*\/#', '/* */', $line);
You can see this working here https://3v4l.org/XmltD
If you don't want the /* either, just change the replace call to this:
$string = preg_replace('#\/\*.+\*\/#', '', $string);
I am having some difficulty with reading info from a text file. Is it possible to use php and get one line at a time, and compare that line to a variable, one character at a time? Every time I add the character searching algorithm it messes up. or does the file reading only do full files/lines/character
ex:
$file=fopen("text/dialogue.txt","r") or exit("unable to open dialogue file");
if($file == true) {
echo "File is open";
fgets($file);
$c = "";
while(!feof($file)) {
$line = fgets($file)
while($temp = fgetc($line)) {
$c = $c . $temp;
//if statement and comparrison
}
}
} else {
echo "File not open";
}
fclose($file);
You may use php file function to read a file line by line
<?php
$lines = file("myfile.txt");
foreach($lines as $line){
## do whatever you like here
echo($line);
}
?>
Please check php manual
http://php.net/manual/en/function.file.php
This code opens a text file, then checks to see if each word in the text file
Exists in a another large 2MB dictionary file.
If it does exist, it stores the line from the dictionary file into a variable.
The code was working, but then began to generate Server 500 errors, and now
It only lists about 7 matches and then loads nothing forever.
It used to list the 1000's of matches and then stop.
$file_handle = fopen("POSdump.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$words= explode(" ", $line );
foreach ($words as $word) {
$word = preg_replace('#[^\w+>\s\':-]#', ' ', $word);
$subwords= explode(" ", $word );
$rawword = $subwords[0];
$poscode = $subwords[1];
$rawword = strtoupper($rawword);
$handle = fopen("dictionary.txt","r"); //
if ($handle) {
while (!feof($handle))
{
$buffer = fgets($handle, 4096);
if (preg_match('#\b'.$rawword.'\b#',$buffer)) {
echo $rawword;
echo "</br>";
}
}
}
}
}
?>
Try closing the file when you are done.
This seems to be a memory_limit error. use ini_set('memory_limit', -1) before starting the process.
I've got a problem where I'm trying to read a text file like this:
Joe
Johnson
Linus
Tourvalds
and while parsing it in php, I need to be able to detect the newlines. I'm trying to correctly define $newline. I'm looping through the array of lines in the $file variable.
while($line = next($file))
if($line = $newline)
echo "new line";
The problem is that I can't seem to match the newline character. I know that it is actually showing up in the $file array, because this:
while($line = next($file))
echo $line;
outputs the file verbatim, with newlines and all. I've already tried "\n", " ", and I'm not sure what to try next. A little help?
$file = file("path/to/file.txt");
// Incase you need to call it multiple times ...
function isNewLine($line) {
return !strlen(trim($line));
}
foreach ($file as $line) {
if (isNewLine($line)) {
echo "new line<br/>";
}
}
Maybe something like this would work for you?
while($line = next($file)) {
if(in_array($line, array("\r", "\n", "\r\n"))) {
echo "new line";
}
}
I think this solution may help you guys. This works if you are parsing csv that is generated from Mac or windows. Reading csv with multilines created in Mac, gives problem i.e. you cannot read each line in a loop but all csv data is read as single line.
This problem is solved by following solution:
//My CSV contains only one column
$fileHandle = fopen("test.csv",'r');
$codesArray = array();
count = 0;
while (!feof($fileHandle) ) {
$line = fgetcsv($fileHandle);
if($line[0]!="") {
$data = str_replace("'", "", (nl2br ($line[0])));
$dataArray = explode('<br />' ,$data );
foreach($dataArray as $data) {
$codesArray[] = trim($data);
}
}
}
echo "<pre>";
print_r($codesArray);