How to remove particular data from file using php - php

Present data in file ---
Kortrijk]]||75,592||74,790||73,777VWVVLG
Hasselt]]||65,503||68,085||70,584VLIVLG
Sint-Niklaas]]||68,277||68,290||70,016VOVVLG
Ostend]]||69,039||67,279||69,115VWVVLG
|22Tournai]]||67,291||67,379||67,844WHTWAL
|23Genk]]||61,532||62,842||64,095VLIVLG
|24Seraing]]||62,832||60,557||61,237WLGWAL
This is the data set i have in my wiki.txt file, i need to remove all content after "]]||" from all lines.
//Require data after code implementation
Kortrijk
Hasselt
Sint-Niklaas
Ostend
|22Tournai
|23Genk
|24Seraing
This is the code i came across, but dont have any idea how to use it in my code, i followed preg_replace, regular expression etc but all going above my head..help me plz and plz let me know any tutorial link that i can follow for these kind of working(specially regular expression for a novice).
$file="wiki.txt";
file_put_contents($file,str_replace('find','replace',file_get_contents($file)));

try:
$arr = file("wiki.txt"); //will give you contents as array
$newContent = "";
foreach($arr as $key => $val) {
$newContent .=substr_replace($val, '', strpos($val, ']'))."\n";
}
//add changed content back to file
file_put_contents("wiki.txt", $newContent);
//result is:
Kortrijk
Hasselt
Sint-Niklaas
Ostend
|22Tournai
|23Genk
|24Seraing

preg_replace('/]]\|\|.*$/m', '', $fnames);
Matches ']]||' literally, then all characters (.*) until the end of a line '$' and replaces them with ''.
Also: Check out this tutorial on RegExp

Rather than "change" the file, you probably want to open the file, read the contents, then write the parts you want to a new file. If everything goes as planned, replace the old file with the new file. Much safer that way.
<?php
$lines = file("input.txt");
$output = "";
foreach ($lines as $line) {
$output .= substr($line, 0, strpos($line, "]")) . "\n";
}
file_put_contents("output.txt", $output);
Lots of ways to solve this.

Related

Editing values received from the database

Through PHP I downloaded an array with product descriptions from the database, but when adding them to the csv file, they contain unnecessary newlines. Is it possible to somehow remove them without interfering with the database (from the php level) ?
I tried to edit according to advice, but unfortunately it does not turn out as it should. I tried str_replace () but also to no avail:
$file_open = fopen("file_empik.csv", "w");
fputcsv($file_open, $heders);
foreach($title_from_shopify_table as $info)
{
$descr = $info['descr'];
str_replace('\n', '', $descr);
print_r($descr);
$line_info = array('', $info['title'], $info['descr'], $info['sku'], $info['imgsrc'], '23%', $info['vendor']);
fputcsv($file_open, $line_info);
}
fclose($file_open);
return $products_data; ```
Thank you for any help
You can stock it to variable, then you'll be able to edit what you want.
Something like
$array = callFromDatabase
foreach($array as $line) {
$line.editMethod // What you want to do ...
}
You can use regex!
This replaces them with a space:
$string = trim(preg_replace('/\s\s+/', ' ', $string));
Here is more information on preg_replace:
https://www.w3schools.com/php/func_regex_preg_replace.asp
Edit: If you are simply wanting to store the data and mess around with it then you should use a variable as #Devinfo_dh has pointed out.

Remove blank lines from txt file keeping carriage returns

I'm afraid this question won't be too popular and possibly to be downvoted, but I have searched and searched in this site (and others too) and I can't find a solution.
I have a text file with, say, this content:
I need to remove blank lines, but keeping the existing carriage returns, like this:
The code I'm using:
if ($file = fopen("file.txt", "r")) {
while(!feof($file)) {
$line = fgets($file);
echo str_replace("\r\n","",$line)
}
fclose($file);
}
As stated above, I have tried with functions like str_replace, preg_replace, and \r\n or \n\n, etc. as characters to replace, but with all of them I'm getting this result:
The blank line is removed as desired, but carriage returns are removed too, which it's not allowed in my case.
So I wonder if anyone could suggest a way to get my goal :) Thanks.
There are bound to be duplicates for the replacing, but simply read into an array and skip the empty lines:
$lines = file("file.txt", FILE_SKIP_EMPTY_LINES):
Then loop the array to echo the lines or implode() to get it back into a string.
#Abracadaver #nogad #GCRdev
I've bee trying your methods, but didn't work for me. I finally found a way (thanks to https://stackoverflow.com/a/20719126), which I let it here if it is useful for someone:
$file = fopen("file.txt","r");
while($line = fgets($file)){
$tempData = nl2br($line);
$tempData = explode("<br />",$tempData);
foreach ($tempData as $val) {
if(trim($val) != '')
{
echo $val."<br />";
}
}
}
fclose($file);

correct regex date pattern for dd/mm/yyyy

I need to update the same line, which is also including a date in dd/mm/yyyy format along with some string, in a group of files. I have checked answers here given to similar questions however couldn’t make any of the patterns suggested run in my code.
My current PHP code is:
<?php
// get the system date
$sysdate = date("d/m/Y");
// open the directory
$dir = opendir($argv[1]);
$files = array();
// sorts the files alphabetically
while (($file = readdir($dir)) !== false) {
$files[] = $file;
}
closedir($dir);
sort($files);
// for each ordered file will run the in the clauses part
foreach ($files as $file) {
$lines = '';
// filename extension is '.hql'
if (strpos($file,".hql") != false || strpos($file,".HQL") != false)
{
$procfile = $argv[1] . '\\' . $file;
echo "Converting filename: " . $procfile . "\n";
$handle = fopen($procfile, "r");
$lines = fread($handle, filesize($procfile));
fclose($handle);
$string = $lines;
// What are we going to change runs in here
$pattern = '[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]';
$replacement = $sysdate;
$lines = preg_replace($pattern, $replacement, $string);
echo $lines;
$newhandle = fopen($procfile, 'w+');
fwrite($newhandle, $lines);
fclose($newhandle);
// DONE
}
}
closedir($dir);
?>
When I run this code on command prompt, it doesn’t give any error message and it seems to be running properly. But once it finishes and I check my files, I see that the content of each file is getting deleted and they all become 0 KB files with nothing in them.
You have no delimiters set in place for your regular expression.
A delimiter can be any (non-alphanumeric, non-backslash, non-whitespace) character.
You want to use a delimiter besides / so you avoid having to escape / already in your pattern.
You could use the following to change your format:
$pattern = '~[0-9]{4}/[0-9]{2}/[0-9]{2}~';
See Live demo
This one also do basic checks (month between 1-12, day between 1-31)
(0(?!0)|[1-2]|3(?=[0-1]))\d\/(0(?!0)|1(?=[0-2]))\d\/\d{4}
See it live: http://regex101.com/r/jG9nD5
You should surround the regular expression with delimiter character.
For example:
$pattern = '![0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]!';
/ is commonly used, but because the regular expression contains / itself, I used ! instead.
Besides the lack of delimiters (# and ~ are favorites, if / is used in the pattern), you are looking for 4 digits at the beginning: yyyy/mm/dd. Decide what you're looking for. You might also be able to do something like
[0-9]{4}/[0-9]{2}/[0-9]{2}
or even
\d{4}/\d{2}/\d{2}
... I know those will work in Perl, but I haven't tried them with PHP (they ought to work, as the "p" in preg stands for Perl, but no guarantees).
Why use regex? Use DateTime class for validation.
var_dump(validateDate('2012-02-28', 'Y-m-d')); # true
var_dump(validateDate('28/02/2012', 'd/m/Y')); # true
var_dump(validateDate('30/02/2012', 'd/m/Y')); # false
function
Your code can be rewritten in short like this:
#!/usr/bin/php
<?php
// get the system date
$sysdate = date('d/m/Y');
// change working directory to the specified one
chdir($argv[1]);
// loop over the *.hql files in sorted order
foreach (glob('*.{hql,HQL}', GLOB_BRACE) as $file) {
echo "Converting filename: $argv[1]\\$file\n";
$contents = file_get_contents($file);
$contents = preg_replace('#\d{4}/\d{2}/\d{2}#', $sysdate, $contents);
echo $contents;
file_put_contents($file, $contents);
}
The problem was with the missing PCRE regex delimiters as others already pointed out. Even after fixing this, the code was not really nice.
The glob and file_get_contents functions are available as of PHP 4.3.0. The file_put_contents function is available as of PHP 5.
glob makes your code more succinct, readable and even portable as you won‘t have to mention directory separator anywhere except the info message. You used \\ but should have used DIRECTORY_SEPARATOR if you wanted your code to be portable.
The file_get_contents function fetches the whole contents of a file as a string. The file_put_contents function does the opposite – stores a string in a file. If you want it in PHP 4, use this implementation:
if (!function_exists('file_put_contents')):
function file_put_contents($filename, $data) {
$handle = fopen($filename, 'w');
$result = fwrite($handle, $data);
fclose($handle);
return $result;
}
endif;
Also notice that the final ?> is not necessary in PHP.

PHP extract data from text file and write to another file

This is my first post on the internet for some assistance with coding so please bear with me!
I have been finding open code on the internet for a few years and modding it to do what I want but I seem to have come up against a wall with this one that I am sure is very simple. If you would please be able to help me it would be very much appreciated.
I have the following page:
<?php
$text = $_REQUEST['message'];
$f = file_get_contents("all.txt");
$f = explode(", ", $f);
function modFile($pos, $tothis, $inthis)
{
foreach($inthis as $pos => $a){
}
$newarr = implode("\r\n", $inthis);
$fh = fopen("example.txt", "w");
fwrite($fh, $newarr);
fclose($fh);
}
modFile(4, '', $f);
I have a file (all.txt) with the following:
11111111111, 22222222222, 33333333333, 44444444444
That I wish to display like this:
11111111111
22222222222
33333333333
44444444444
and to add a space then some text after each number where the text is the same on each line:
11111111111 text here
22222222222 text here
33333333333 text here
44444444444 text here
I have an html form that passes the custom text to be appended to each line.
I need to keep the file all.txt intact then save the newly formatted file with a different name.
I have tried putting variables into the implode where I currently have the "\r\n" but this does not work.
Any help very much appreciated.
Thanks in advance!
A few notes about your code: You are passing $pos to the function but it will get overwritten in the foreach. Also the foreach is empty, so what's it good for? And I don't see you use $text anywhere either.
To achieve your desired output, try this instead:
file_put_contents(
'/path/to/new.txt',
preg_replace(
'/[^\d+]+/',
' some text' . PHP_EOL,
file_get_contents('all.txt')
)
);
The pattern [^\d+]+ will match any string that is not a consecutive number and replace it with "some text " and a new line.
A somewhat more complicated version achieving the same would be:
file_put_contents(
'/path/to/new.txt',
implode(PHP_EOL, array_map(
function ($number) {
$message = filter_var(
$_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS
);
return sprintf('%s %s', trim($number), $message);
},
array_filter(str_getcsv(file_get_contents('/path/to/all.txt')))
)
));
This will (from the inside out):
Load the content of all.txt and parse it as CSV string into an array. Each array element corresponds to a number.
Each of these numbers is appended with the message content from the POST superglobal (you dont want to use REQUEST).
The resulting array is then concatenated back into a single string where the concatenating character is a newline.
The resulting string is written to the new file.
In case the above is too hard to follow, here is a version using temp vars and no lambda:
$allTxtContent = file_get_contents('/path/to/all.txt');
$numbers = array_filter(str_getcsv($allTxtContent));
$message = filter_var($_POST['message'], FILTER_SANITIZE_SPECIAL_CHARS);
$numbersWithMessage = array();
foreach ($numbers as $number) {
$numbersWithMessage[] = sprintf('%s %s', trim($number), $message);
};
$newString = implode(PHP_EOL, $numbersWithMessage);
file_put_contents('/path/to/new.txt', $newString);
It does the same thing.
Your foreach() closing brace is on the wrong place. You've missed the exact part of running the execution of the new file creation. Here:
$text = $_REQUEST['message'];
$f = file_get_contents("all.txt");
$f = explode(", ", $f);
function modFile($pos, $tothis, $inthis, $text){
$fh = fopen("example.txt", "w");
foreach($inthis as $pos => $a){
$newarr = $a." ".$text."\r\n";
fwrite($fh, $newarr);
}
fclose($fh);
}
modFile(4, "", $f, $text);
This is for formatting your new file as you desire, however, you're not passing the new $text['message'] you want to append to your new file. You could either modify your mod_file() method or pass it within the foreach() loop while it runs.
EDIT* Just updated the whole code, should be now what you aimed for. If it does, please mark the answer as accepted.

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