Is there an equivalent to PERL's TIE in php? I'd like to see if a string(single word) is in a file where each line is a single word/string. If it is, I'd like to remove the entry. This would be very easy to do in Perl but unsure how I would do this in PHP.
Depending on how you read the file will determine how you remove the entry.
Using fgets:
$filtered = "";
$handle = fopen("/file.txt", "r");
if ($handle) {
// Read file line-by-line
while (($buffer = fgets($handle)) !== false) {
if (strpos($buffer, "replaceMe") === false)
$filtered .= $buffer;
}
}
fclose($handle);
Using file_get_contents:
filterArray($value){
return (strpos($value) === false);
}
// Read file into a string
$string = file_get_contents('input.txt');
$array = explode("\n", $string);
$filtered = array_filter($array, "filterArray");
Using file:
function filterArray($value){
return (strpos($value) === false);
}
// Read file into array (each line as an element)
$array = file('input.txt', FILE_IGNORE_NEW_LINES);
$filtered = array_filter($array, "filterArray");
Note: Each method assumes that you want to remove the entire entry if it contains a single word.
Related
I'm writing a PHP script to search for a few lines in a pcap file. This pcap file will be piped through tail -> PHP.
I need to find a few lines like (Host: www.google.com) or (Domain: amazon.com) etc..
I'm new with PHP and struggling to get this code working, the actual output of all the fetched data need to be inserted into a SQL DB. I've used regex to filter out the binary stuff from the pcap.
I've tried multiple loops like the wile, foreach, for, but I'm not getting the clue how to do this in my script.
The code that I have so far is:
<?php
$handle = fopen('php://stdin', 'r');
$line = fgets ($handle, 1000);
$search1 = 'Location';
$search2 = 'Host:';
$search3 = 'User';
$search4 = 'Cookie';
$search5 = 'Domain:';
$matches = array();
$regex = '/[^a-zA-Z0-9\s\D\#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/';
if ($handle){
while ($handle) {
$buffer = fgets($handle);
if(strpos($buffer, $search1) !== FALSE) {
$res = preg_replace($regex, "", $buffer);
$matches[] = $res;
print_r($res). "\n";
}
}
fclose($handle);
}
?>
I've read many posts on the internet, but couldn't find any solution or I've not enough knowledge about PHP to get this done. Can anyone help me with this?
If it's working for first then loop it think about algorithm always
$handle = fopen('php://stdin', 'r');
$line = fgets ($handle, 1000);
$search = ['Location','Host:','User','Cookie','Domain:'];
$matches = array();
$regex = '/[^a-zA-Z0-9\s\D\#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/';
if ($handle){
while ($handle) {
$buffer = fgets($handle);
foreach($search as $seek){
if(strpos($buffer, $seek) !== FALSE) {
$res = preg_replace($regex, "", $buffer);
$matches[] = $res;
print_r($res). "\n";
}
}
}
fclose($handle);
}
?>
I am using a simple php translation class and I have about more than 2000 php files which the translation class was implemented and new strings are as well implemented so I need an updated text file with all the translation strings.
I need to get all the translated values from each php file and save it into a text file without any repeated value.
Translation class
<?php $translate->__('Calendar'); ?>
So I need to get Calendar saved into a txt file and this should be done for all the files in all folders.
Everything in between $translate->__(' and ') should be saved.
The below code not working for some reason.
$fn = $_SERVER['DOCUMENT_ROOT']."/apps/test/test2/calendar.php";
$handle = fopen($fn, 'r');
$valid = false;
$search = "\/\\$translate\\-\\>__\\(\\'(.*?)'\\)\/g";
while (($buffer = fgets($handle)) !== false) {
if(preg_match_all($search, $buffer, $m)) {
print $m[1];
} else {
}
}
fclose($handle);
You're extracting strings with this pattern:
/\$translate\-\>__\(\'(.*?)'\)/g
extract all of matched items and save them any where.
Demo and Details : https://regex101.com/r/LzMyJY/1
$fn = $_SERVER['DOCUMENT_ROOT']."/apps/test/test2/calendar.php";
$handle = fopen($fn, 'r');
$valid = false;
$search = "/\\".'$'."translate\\-\\>__\\(\\'(.*?)'\\)/g";
while (($buffer = fgets($handle)) !== false) {
if(preg_match_all($search, $buffer, $m)) {
print $m[1];
} else {
}
}
fclose($handle);
Note:
In use of regex patterns, remember handle backslash \ when putting pattern in ".." (change all \ to \\ in this case)
If using '...' don't change \ with \\ !
I have a text file that stores lastname, first name, address, state, etc as a string with a | delimiter and each record on a separate line.
I have the part where I need to store each record on a new line and its working fine; however, now I need to be able to go back and update the name or address on a particular line and I can't get it to work.
This how to replace a particular line in a text file using php? helped me here but I am not quite there yet. This overwrites the whole file and I lose the records. Any help is appreciated!
After some edit seems to be working now. I am debugging to see if any errors.
$string= implode('|',$contact);
$reading = fopen('contacts.txt', 'r');
$writing = fopen('contacts.tmp', 'w');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if(stripos($line, $lname) !== FALSE) {
if(stripos($line, $fname) !== FALSE) {
$line = "$string";
$replaced = true;
}
}
fwrite($writing, "$line");
//fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('contacts.tmp', 'contacts.txt');
} else {
unlink('contacts.tmp');
}
It seems that you have a file in csv-format. PHP can handle this with fgetcsv() http://php.net/manual/de/function.fgetcsv.php
if (($handle = fopen("contacts.txt", "r")) !== FALSE) {
$data = fgetcsv($handle, 1000, '|')
/* manipulate $data array here */
}
fclose($handle);
So you get an array that you can manipulate. After this you can save the file with fputcsv http://www.php.net/manual/de/function.fputcsv.php
$fp = fopen('contacts.tmp', 'w');
foreach ($data as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Well, after the comment by Asad, there is another simple answer. Just open the file in Append-mode http://de3.php.net/manual/en/function.fopen.php :
$writing = fopen('contacts.tmp', 'a');
I am using fopen to reach my PHP file :
$readFd = #fopen($file, 'r+');
I would like to search this file for the function call parent::process();
And if this exists I would then insert a new function call after this.
I have tried using preg_replace but it does not seem to match parent::process();
For example the result I need is this.
public function process() {
parent::process();
$this->newFunction();
}
Then to write the to the file I am using :
fwrite($readFd, $content);
I guess I must be missing something important with regex.
Hopefully someone can point me in the right direction.
I would use the php function fgets to read every in the file one by one until you reach the line you need. And then your pointer will be after that line where you can write your own line.
EDIT
I was wrong, when you write something to a file at a specific point, everything after that point is lost. So I did a little testing and came up with this:
$handle = fopen($file,"r+");
$lines = array();
while(($line = fgets($handle)) !== false) {
$lines[] = $line;
if(strpos($line, 'parent::process()')) {
$lines[] = '$this->newFunction();';
}
}
fseek($handle, 0); // reset pointer
foreach($lines as $line) {
fwrite($handle, $line);
}
fclose($handle);
I hope this solves your problem.
I came up with the solution however your code seems much shorter so I will try your solution tomorrow.
if(! $readFd = #fopen($file, "r+"))
return FALSE;
$buffer = fread($readFd, 120000);
fclose($readFd);
$onDuplicate = FALSE;
$lines = explode("\n", $buffer);
foreach($lines AS $key => $line) {
if(strpos($line, "newFunction()")) {
$onDuplicate = TRUE;
}
if(strpos($line, "parent::process()")) {
$lines[$key] = "\t\tparent::process();\n\t\t//\$this->newFunction();\n";
}
}
if(! $onDuplicate) {
$readFd = fopen($file, "w");
$buffer = implode("\n", $lines)."\n";
fwrite($readFd, $buffer);
fclose($readFd);
} else {
var_dump('changes are already applied');
}
Thanks for all your help!
I have a file that is sorted using natsort()...(In ascending order)
But actually i want to sort it in descending order..
I mean the last line of document must be first line and vice versa
Pls let me know is there any function or snippet to achive this..
I'm not that good at php, Appreciate all responses irrespective of quality...Thank You
use natsort() and than use function array_reverse().
Also refer link
PHP Grab last 15 lines in txt file
it might help you.
array_reverse will give the contents in descending order
$reverse = array_reverse($array, true);
Whilst not the most efficient approach for a large text file, you could use file, array_reverse and file_put_contents to achieve this as follows...
<?php
// Fetch each line from the file into an array
$fileLines = file('/path/to/text/file.txt');
// Swap the order of the array
$invertedLines = array_reverse($fileLines);
// Write the data back to disk
file_put_contents('/path/to/write/new/file/to.txt', $invertedLines);
?>
...to achieve what you're after.
For longer files:
<?php
function rfopen($path, $mode)
{
$fp = fopen($path, $mode);
fseek($fp, -1, SEEK_END);
if (fgetc($fp) !== PHP_EOL) fseek($fp, 1, SEEK_END);
return $fp;
}
function rfgets($fp, $strip = false)
{
$s = '';
while (true) {
if (fseek($fp, -2, SEEK_CUR) === -1) {
if (!empty($s)) break;
return false;
}
if (($c = fgetc($fp)) === PHP_EOL) break;
$s = $c . $s;
}
if (!$strip) $s .= PHP_EOL;
return $s;
}
$file = '/path/to/your/file.txt';
$src = rfopen($file, 'rb');
$tgt = fopen("$file.rev", 'w');
while ($line = rfgets($src)) {
fwrite($tgt, $line);
}
fclose($src);
fclose($tgt);
// rename("$file.rev", $file);
Replace '/path/to/your/file.txt' with the path to your file.
Uncomment the last line to overwrite your file.