PHP: Replace line in a file or add if not found - php

I have a file (messages.txt) that looks something like this:
112233|A line of text here.
aabbcc|More text here.
223344|And the list goes on...
and code like this that works as expected:
$filename = 'messages.txt';
$data = file($filename);
file_put_contents($filename, implode('',
array_map(function($data) {
return stristr($data,'aabbcc') ? "aabbcc|This would be a NEW line.\n" : $data;
}, file($filename))
));
So this will replace the line where it finds aabbcc with a new one.
How do I edit this so that if the line isn't found, it would add it at the end of the txt file? Is there an easy way to do this or would I need to alter the code quite a bit to make it work? Thanks.

You can do something like this:
$message_exists = false;
$filename = 'messages.txt';
$data = file($filename);
file_put_contents($filename, implode('',
array_map(function($data) use (&$message_exists){
$result = substr($data, 0, strlen('aabbcc|')) === 'aabbcc|';
if($result)
{
$message_exists = true;
}
return $result ? "aabbcc|This would be a NEW line.\n" : $data;
}, file($filename))
));
if(!$message_exists)
{
file_put_contents($filename, "aabbcc|This would be a NEW line.\n", FILE_APPEND);
}

Related

how to return an array in php file

I have following array in one of my php file and i want to return that through another file
set-info.php
<?php
return [
'email' => [
'mail-to#mail.com',
'mail-from#mail.com',
]
this is what i tried
public function getInfo()
{
//read file contents from file
$filename =$_SERVER['DOCUMENT_ROOT'].'/set-info.php';
$filename = str_replace(" ", "", $filename);
if (file_exists($filename)) {
$str = file($filename);
$str = file_get_contents($filename);
return $str;
}
}
im getting whole contents with php tags as output.
how to get only php array ? pls advice
];
Try to use:
public function getInfo()
{
//read file contents from file
$filename =$_SERVER['DOCUMENT_ROOT'].'/set-info.php';
$filename = str_replace(" ", "", $filename);
if (file_exists($filename)) {
$str = (include $filename);
return $str;
}
}
You need to use include for to get that array that you can use in PHP. With file_get_contents you get the content of the file as string.
Change your method like this:
public function getInfo()
{
$info = include 'set-info.php';
//Now $info will be the array from set-info.php file.
}
You can check more examples here: http://php.net/manual/en/function.include.php

php file_put_content overwrite

So i found this code which lets be write to a specific line
function SetSiteName(){
global $session, $database, $form;
$filepathname = "include/classes/constants.php";
$target = 'sitename';
$newline = 'define("sitename", "Testing.");';
$stats = file($filepathname, FILE_IGNORE_NEW_LINES);
$offset = array_search($target,$stats) +32;
array_splice($stats, $offset, 0, $newline);
file_put_contents($filepathname, join("\n", $stats));
header("Location: ".$session->referrer);
}
however it will not overwrite whats on that line it'll go to the next line and put the data in.. I'd like to make it overwrite what currently is on that line?
Any thoughts?
You can overwrite a line of a file with this code.
$filename = "file.txt";
$content = file_get_contents($filename);
$lines_array = explode(PHP_EOL, $content);
//overwrite the line that you want.
$lines_array[5] = "New text at line 6!";
file_put_contents($filename, implode(PHP_EOL, $lines_array));

How can I edit the content of a ini file?

I would like to be able to edit a config file for a server application using php. The config file is as follows:
include=sc_serv_public.conf
streamid_2=2
streampath_2=/relay
streamrelayurl_2=http://<full_url_of_relay_including_port>
;allowrelay=0
;allowpublicrelay=0
I would like to edit the line:
streamrelayurl_2=http://<full_url_of_relay_including_port>
and then save the file.
I am currently using:
$data = file_get_contents("sc_serv.conf"); //read the file
$convert = explode("\n", $data); //create array separate by new line
to open the file, but now I dont know how to edit it.
As an alternative, you could just use file() instead. This just loads it up into array form, no need to explode. Then after that, you just loop the elements, if the desired needle is found, overwrite it, the write the file again:
$data = file('sc_serv.conf', FILE_IGNORE_NEW_LINES); // load file into an array
$find = 'streamrelayurl_2='; // needle
$new_value = 'http://www.whateverurl.com'; // new value
foreach($data as &$line) {
if(strpos($line, 'streamrelayurl_2=') !== false) { // if found
$line = $find . $new_value; // overwrite
break; // stop, no need to go further
}
}
file_put_contents('sc_serv.conf', implode("\n", $data)); // compound into string again and write
You can use file() to read the file content to an array, then you can iterate trough the array with foreach() searching with the strstr() function the line that have your URL (in this case is in the var $id_change) and change the value. Then as you found what you needed, you end the foreach() with break. And make your string to save in the file with implode() and save the string to the config file with file_put_content().
See the code:
<?php
$new_url = 'http://www.google.com';
$id_change = 'streamrelayurl_2';
$file = "sc_serv.conf";
$data = file($file); //read the file
foreach($data as $key => $value) {
if(strstr($value, $id_change)) {
$info = $id_change . '=' . $new_url . "\n";
$data[$key] = $info;
break;
}
}
$data = implode("", $data);
file_put_contents($file, $data);
?>
Output:
include=sc_serv_public.conf
streamid_2=2
streampath_2=/relay
streamrelayurl_2=http://www.google.com
;allowrelay=0
;allowpublicrelay=0

Reversing A text file using PHP

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.

How do I find the line in a text file beginning with 5678 and replace it with nothing using php?

Lets say the text file contains:
56715:Jim:12/22/10:19
5678:Sara:9/04/08:92
53676:Mark:12/19/10:6
56797:Mike:12/04/10:123
5678:Sara:12/09/10:49
56479:Sammy:12/12/10:645
56580:Martha:12/19/10:952
I would like to find the lines beginning with "5678" and replace them with nothing, so the file will now contain only:
56715:Jim:12/22/10:19
53676:Mark:12/19/10:6
56797:Mike:12/04/10:123
56479:Sammy:12/12/10:645
56580:Martha:12/19/10:952
Thanks.
// The filename
$filename = 'filename.txt';
// Stores each line into an array item
$array = file($filename);
// Function to return true when a line does not start with 5678
function filter_start($item)
{
return !preg_match('/^5678:/', $item);
}
// Runs the array through the filter function
$new_array = array_filter($array, 'filter_start');
// Writes the changes back to the file
file_put_contents($filename, implode($new_array));
Well, just use preg_replace:
$data = file_get_contents($filename);
$data = preg_replace('/^5678.*(\n|$)/m', '', $data);
Note the m modifier. That puts PCRE into multiline mode, where ^ matches the start of the document, and after any new-line character (and $ matches the end of the document, and before any new-line character)...
Also, depending on your exact needs, you could create a stream filter:
class LineStartFilter extends php_user_filter {
protected $data = '';
protected $regex = '//';
public function filter($in, $out, &$consumed, $closing) {
var_dump($this->regex);
while ($bucket = stream_bucket_make_writeable($in)) {
$bucket->data = preg_replace($this->regex, '', $bucket->data);
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
public function onCreate() {
list($prefix, $data) = explode('.', $this->filtername);
$this->data = $data;
$this->regex = '/^'.preg_quote($data, '/').'.*(\n|$)/m';
}
}
stream_filter_register('linestartfilter.*', 'LineStartFilter');
Then, just do this when you want to read the file:
$f = fopen('test.txt', 'r');
stream_filter_append($f, 'linestartfilter.5678');
fpassthru($f);
fclose($f);
That will output your requested string. And if you want to write to another file (copy it):
$f = fopen('test.txt', 'r');
stream_filter_append($f, 'linestartfilter.5678');
$dest = fopen('destination.txt', 'w');
stream_copy_to_stream($f, $dest);
fclose($f);
fclose($dest);
preg_replace('~5678:[^\n]+?\n~', '', $text);
If your text ends with \n, otherwise convert the line endings first.
Tim Cooper just reminded me what file() does :)
$lines = file($filename);
$lines = preg_grep('/^5678/', $lines, PREG_GREP_INVERT);
$file = implode($lines);
file_put_contents($filename, $file);

Categories