PHP - Search File for Contents - php

I have a PHP script that reads the contents of a file and stores it into a variable. I want to split the text stored by the new line entries and then search the array[0] value for a specific value.
That is my idea. Here is my situation.
I have a directory file with specific entries.
Entry1_two_term3_stuff
Entry2_two_term3_stuff
Entry3_two_term3_stuff
This will be stored into a variable. How do I search this for Entry2 and then get the whole line to work with?

If you can, use the file() function to load the file into array, already split by newlines:
$lines = file('filename.txt');
If not, you can use
$lines = explode("\n", $contents);
You might want to use \r\n if you're on Windows and file contains CR characters.
To search the array, use foreach:
foreach ($lines as $ix => $line)
if (strpos ($line, 'string') !== false)
$lines[$ix] = ...new version of line...
In the end, write contents back to some file:
$fp = fopen('file.txt', 'w+');
foreach ($lines as $line)
fputs($fp, $line);
fclose($fp);

You could search the directories with RecursiveDirectoryIterator, and search the files contents individually with preg_match_all

Related

trim function not working for string array

This is a really odd behavior that I can't explain. I have a CSV file that I'm trying to format. The lines could have trailing ','s that I want to remove.
$lines = explode(PHP_EOL, $csv);
$csv = '';
foreach($lines as $line) {
$csv .= trim($line, ',') . PHP_EOL;
}
The trim is not doing anything and just returning the line back as it is. Just to make sure I copied a line from the csv trim("a,b,c,d,,", ','); which works fine. Can anyone tell me why the above code won't work?
If the CSV file was created on a different operating system, it may use different line breaks than PHP_EOL. So trim any line break characters in addition to commas.
foreach($lines as $line) {
$csv .= trim($line, ",\r\n") . PHP_EOL;
}
Don't manually edit the CSV file. Parse it into an array, then edit the array. Then you can write the modified array back to a CSV file.
You can use fputcsv to write the data to a file, or str_putcsv (a custom function).
$newData = [];
$data = array_map('str_getcsv', $lines); // parse each line as a CSV
foreach ($data as $row) {
$row = array_filter($row); // remove blank values
// for some dumb reason, php has `str_getcsv` but not `str_putcsv`
// so let's use `str_putcsv` from: https://gist.github.com/johanmeiring/2894568
$newData[] = str_putcsv($row);
}
$newData = implode(PHP_EOL, $newData);

Remove Line from String within txt file

Currently I have a code, which displays data from a txt file, and randomizes it after converting it into an array.
$array = explode("\n", file_get_contents('test.txt'));
$rand_keys = array_rand($array, 2);
I am trying to make it so that, after this random value is displayed.
$search = $array[$rand_keys[0]];
We're able to store this into another txt file such as completed.txt and remove the randomized segment from our previous txt file. Here's the approach I tried, and surely didn't work out with.
$a = 'test.txt';
$b = file_get_contents('test.txt');
$c = str_replace($search, '', $b);
file_put_contents($a, $c);
Then to restore into a secondary file, I was messing with something like this.
$result = '';
foreach($lines as $line) {
if(stripos($line, $search) === false) {
$result .= $search;
}
}
file_put_contents('completed.txt', $result);
This actually appears to work to some extent, however when I look at the file completed.txt all of the contents are EXACTLY the same, and there's a bunch of blank spaces being left behind within test.txt
There are some better ways of doing it (IMHO), but at the moment you are just removing the actual line without the new line character. You may also find it will replace other lines as it just replaces the text without any idea of content.
But you will probably fix your code with the addition of replacing the new line...
$c = str_replace($search."\n", '', $b);
An alternative way of doing it is...
$fileName = 'test.txt';
$fileComplete = "completed.csv";
// Read file into an array
$lines = file($fileName, FILE_IGNORE_NEW_LINES);
// Pick a line
$randomLineKey = array_rand($lines);
// Get the text of that line
$randomLine = $lines[$randomLineKey];
// Remove the line
unset($lines[$randomLineKey]);
// write out new file
file_put_contents($fileName, implode(PHP_EOL, $lines));
// Add chosen line to completed file
file_put_contents($fileComplete, $randomLine.PHP_EOL, FILE_APPEND);

remove everything after first space on each line of this text file

In PHP, how can one edit a text file and save it so that everything after the first space is removed?
In other words, so that each line only has its first word?
For example, if the text file looked like this:
Adi NNP
Adia NNP
Adios NNP FW
Adios-Direct NNP
Adios-On NNP
Adios-Rena NNP
Adios-Trustful NNP
Adirondack NNP
Adirondacks NNPS
Adjoining VBG
Adjournment NN
after executing the script, the text file would look like this:
Adi
Adia
Adios
Adios-Direct
Adios-On
Adios-Rena
Adios-Trustful
Adirondack
Adirondacks
Adjoining
Adjournment
How I would approach this would be to open the file, read it in, and take each line and store it in an array. Then replace everything after the first space with nothing. And lastly, save the edited array to a new file.
Is there a better way to do it than that?
All I know how to do in the above method is everything except the last two tasks. I would do it like so:
$file = array();
$lines = file('file.txt');
foreach($lines as $line){
array_push($file, $line);
}
// now travel through $file and replace everything after first space with nothing
// travel though $file again, but write each element as a new line in a .txt file
You can use explode() to separate the line by spaces. Then you can immediately write the string back to a file, no second loop is required:
$file = array();
$lines = file('file.txt');
$new_file = fopen('new.txt', 'w+');
foreach($lines as $line){
$bits = explode(' ', $line);
fwrite($new_file, $bits[0] . PHP_EOL);
}
fclose($new_file);
You can do it in the same line: just replace array_push($file, $line) with...
$file[] = strtok($line, ' ');
It can be written even more compact with help of array_map:
$lines = array_map(function($line) {
return strtok($line, ' ');
}, file('file.txt'));
... or you can write it back immediately, as shown in #hek2mgl answer.
You can bypass arrays entirely and do this with a simple regular expression:
// Read in contents into a variable
$data = file_get_contents('input.txt');
// Drop the space and everything after on each line
$data = preg_replace('/ .*$/m', '', $data);
// Dump contents to file (change this to input.txt if you want to overwrite the file)
file_put_contents('output.txt', $data);

how to replace some part of text from the text file in php

I'm trying to delete/edit some portion of text from text file, like if I have 10 lines in my text file then I want to edit 5th line or delete 3rd line without affecting any other line.
Currently what I'm doing
1. open text file and read data in php variable
2. done editing on that variable
3. delete the content of text file.
4. write new content on it
but is there any way to doing that thing without deleting whole content or by just edit those content?
my current code is like this
$file = fopen("users.txt", "a+");
$data = fread($file, filesize("users.txt"));
fclose($file);
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", "");
$file = fopen("users.txt", "a+");
fwrite($file, $newdata);
fclose($file);
You could shorten that to:
$data = file_get_contents("users.txt");
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", $newdata);
$str = '';
$lines = file("users.txt");
foreach($lines as $line_no=>$line_txt)
{
$line_no += 1; // Start with zero
//check the line number and concatenate the string
if($line_no == 5)
{
// Append the $str with your replaceable text
}
else{
$str .= $line_txt."\n";
}
}
// Then overwrite the $str content to same file
// i.e file_put_contents("users.txt", $str);
I have added solution as per my understanding, Hope it will help!!!
You can work on each line:
$lines = file("users.txt");
foreach($lines as &$line){
//do your stufff
// $line is one line
//
}
$content = implode("", $lines);
//now you can save $content like before
If you've only got 10 lines in your text file, then unless they are very long lines you're changing the amount of physical I/O required to change the contents (disks will only read/write data one physical sector at a time - and the days of 512byte sectors are long gone).
Yes, you can modify a large file by only writing the sectors which have changed - but that requires that you replace the data with something the same size to prevent framing errors (in PHP using fopen with mode c+, fgets/fseek/fwrite/ftell, fclose).
Really the corect answer is to stop storing multivalued data in a text file and use a DBMS (which also solves the concurrency issues).

PHP Parse File, replacing not required items going wrong

I'm trying to parse each IP line from the following file (loading from the web) and I'm going to store the values in database so i'm looking to put them in to an array.
The file its loading has the following source:
12174 in store for taking<hr>221.223.89.99:8909
<br>123.116.123.71:8909
<br>221.10.162.40:8909
<br>222.135.5.38:8909
<br>120.87.121.122:8909
<br>118.77.254.242:8909
<br>218.6.19.14:8909
<br>113.64.124.85:8909
<br>123.118.243.239:8909
<br>124.205.154.181:8909
<br>124.117.13.116:8909
<br>183.7.223.212:8909
<br>112.239.205.245:8909
<br>118.116.235.156:8909
<br>27.16.28.174:8909
<br>222.221.142.59:8909
<br>114.86.40.251:8909
<br>111.225.105.142:8909
<br>115.56.86.62:8909
<br>59.51.108.142:8909
<br>222.219.39.194:8909
<br>114.244.252.246:8909
<br>202.194.148.41:8909
<br>113.94.174.239:8909
<br><hr>total£º 24¡£
So I guess I'm looking to take everything between the <hr>'s and add each line line by line.
However doing the following doesn't seem to be working (in terms of stripping it the parts i dont' want)
<?php
$fileurl = "**MASKED**";
$lines = file($fileurl);
foreach ($lines as $line_num => $line) {
$line2 = strstr($line, 'taking', 'true');
$line3 = str_replace($line2, '', $line);
print_r($line3);
}
?>
If you want to add the values to an array, why not doing that directly inside the loop? I'd do something like this:
$output = array();
foreach ($lines as $line) {
if(preg_match("/<br>\d/", $line)) {
$output[] = substr($line, 4);
}
}
print_r($output);
Look into PHP function explode: http://www.php.net/manual/en/function.explode.php
It can take a string, and create an array out of it, by splitting at a specific character. In your case, this might be <br>
Also, trim function can get rid of the whitespace when needed.

Categories