In a txt file, there's the following:
Field1:Field2:Field3:Field4
Data1:Data2:Data3:Data4
How to get the text which is just after "Field1" which is "Field2" and without getting the ":" which is before "Field3" using PHP ?
NOTICE: "Field" won't be a constant string.
EDIT: I want to do something like searching for "Field2" and doing that on it's line only. So I don't want to do that for "Data" too !
Thanks.
EDIT: The main goal I wanted to ask this question for is:
IGNORE IF YOU WANT THE ANSWER, THE ANSWER IS BELOW:
I'm developing an AdminCP for my project, and if the administrator typed "User1" in a HTML form in the AdminCP it must return "This user is suspended!" if the line in the txt file was "User1:suspended:24/01/2012" .
While the format of users in the txt file is:
USERNAME:STATUS:REGISTRATION DATE
User1:suspended:24/01/2012
(All the texts and strings are just examples).
So in the below answer ... $searchfor = 'Field2'; must be $searchfor = $_POST['username']; for example.
And I wanted to use:
if( $data[1]=="suspended" ) {
echo "The user which owns ".$data[0]." is suspended!";
}
While $data[0] is the username (User1), and $data[1] is the status (suspended).
Thanks to #MagnusEriksson and PHP to search within txt file and echo the whole line . I just discovered the solution by myself:
<?php
$file = 'test.txt';
$searchfor = 'Field2';
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
preg_match_all($pattern, $contents, $matches);
$wholeLine = implode("\n", $matches[0]);
$data = explode(":", $wholeLine);
echo $data[0]; // Field1
echo $data[1]; // Field2
?>
Related
I'm trying to parse csv using str_getcsv in the following manner however I'm running into two problems (below).
$url = 'http://my.events.calendar/api/csv?mycalendarquery';
$response = wp_remote_get($url);
$response_body = $response['body']; // this is a really long string
$parsed_string = str_getcsv($response_body, ',', '"');
$full_events_array = array_chunk($parsed_string, 11);
Problem 1 - I can't use explode because one of the fields in the csv is "Description" which contains many/lengthy prose descriptions of events. Naturally these include commas, new lines, returns, etc...
Problem 2 - This is the one I have a question about. The categories (headers?) for the csv file are "Subject", "Date", (more things here...) "Description", "Calendar Address". However the last one doesn't have a comma after it. So, the entries for "Subject" and "Calendar" address are being combined like this -
array(11) {
[0] =>
string(32) "Calendar Address
"Application Due"" // this pattern happens for every event but with a url instead.
// Yes, I know this looks wrong in the code block, but this is exactly how the data is coming in (complete with the double quotes).
How do I parse this so that Calendar Address and Application Due are separated?
For reference, I've also tried str_getcsv($response_body, '"', ','); str_getcsv($response_body, ',', '"', '\n'); and several other combinations. Thanks for the help!
This script will read the CSV file into 251 rows of 12 elements each.
<?php // demo/temp_44414553.php
/**
* https://stackoverflow.com/questions/44414553/parsing-csv-where-the-last-header-is-followed-by-a-space?noredirect=1#comment75830321_44414553
*/
error_reporting(E_ALL);
// UNABLE TO ACCESS: http://events.uconn.edu/exports-2017-05-31-2017-07-01.csv
// COPY MADE HERE FROM THE DOWNLOAD LINK
$url = 'storage/exports-2017-05-31-2017-07-01.csv';
$csv = file_get_contents($url);
echo $csv;
$fpr = fopen($url, 'r');
if (!$fpr) trigger_error("Unable to open $url", E_USER_ERROR);
$kount = 0;
while (!feof($fpr))
{
$row = fgetcsv($fpr);
$kount++;
if (!$row) break;
echo PHP_EOL . count($row);
}
echo PHP_EOL . "There are $kount rows in the CSV at $url";
I have a text file that contains various file absolute path along with other data. Now I need to write a php script to extract only the absolute file path excluding all the other text.
My file looks like
File:
E:\htdocs\DataSet\f1.php
Some text
some more text
* even more text
*
* text again
o E:\xampp\htdocs\DataSet\f2.php
o E:\xampp\htdocs\DataSet\f3.php
I want to extract
E:\htdocs\DataSet\f1.php
E:\xampp\htdocs\DataSet\f2.php
E:\xampp\htdocs\DataSet\f3.php
Basically string/sentence that begins win "E:" and ends with ".php"
Although, the problem is simple but after searching and trying I am not able to find the solution right now...please help!
You need regex with look ahead, this seems to work:
<?php
$s = file_get_contents('input.txt');
if (preg_match_all('/E\:.*(?!\.php)/', $s, $matches)) {
$paths = current($matches);
}
var_dump($paths);
You can use regex for this:
$data = file_get_contents("path_to_your_data");
$pattern = '/E:.+\.php/';
preg_match_all($pattern, $data, $matches);
print_r($matches);
This might be work.
$filename = "Your file name";
$string = file_get_contents($filename);
preg_match_all("/E\:.*(?\.php)/", $string, $data);
I have a txt file populated with line of numbers... I have a code wherein the user can filter particular lines in the txt file
CODE for FILTERING:
<?php
$file = 'upload/filter.txt';
$searchfor = $_POST['search'];
$btn = $_POST['button'];
$sum = 0;
if($btn == 'search') {
//prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else{
echo "No matches found";
}
}
?>
for example the result of the filtering will now produce 4 lines out of 1,000,000 lines from the text file
0100002291310106200140001020055460000000001000000072860103508104
0100002291320106200140001020055460000000005000000072860103508101
0100002291330106200140001020055460000000001000000072860103508102
0100002291340106200140001020055460000000005000000072860103508109
i need a code that will select only particular column and add them together using PHP code... example i only want to add columns 1-10 so the structure will look like this from the lines given above
sructure:
0100002291
0100002291
0100002291
Please Help
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.
This code below can migrate the two variables from one file into the other.
<?php
$file = 'somefile.txt';
// Open the file to get existing content
$current = fopen($file,'a');
// Append a new person to the file
$firstname .= "aiden\n";
$secondname .= "dawn\n";
$currentContent = file_get_contents($file);
// Write the contents back to the file
$fileFound = 'people.txt';
$newFile = fopen($fileFound,'a');
//if $current and $nextcurrent is found in the somefile.txt it will transfer the content to people.txt
if (strpos($currentContent,$firstname) !== 0)
{
if (strpos($currentContent,$secondname) !== 0)
{
fwrite($newFile, $currentContent."\n");
} // endif
}// endif
?>
The next problem is, how am i able to migrate the texts from identifier one up to identifiers two?
I guess I'll have to use substr or a strrpos string here.
Help Please :)
I'm having a hard time understanding the problem but looks like you're trying to include anything between 'aiden' and 'dawn' from a file and write the result into a new file.
Give a shot for this one
$firstIdentifier = 'aiden';
$secondIdentifier = 'dawn';
$currentContent = str_replace("\n", "", file_get_contents('sourcefile.txt'));
$pattern = '/('.$firstIdentifier.')(.+?)('.$secondIdentifier.')/';
//get all text between the two identifiers, and include the identifiers in the match result
preg_match_all($pattern, $currentContent , $matches);
//stick them together with space delimiter
$contentOfNewFile = implode(" ",$matches[0]);
//save to a new file
$newFile = fopen('destinationFile.txt','a');
fwrite($newFile, $contentOfNewFile);
You don't need fopen when you are using file_get_contents
Instead of using a delimiter I'd suggest you just serialize your variables
In file 1:
file_put_contents('somefile.txt',serialize(array($firstname,$lastname)));
In file 2:
list($firstname,$lastname) = unserialize(file_get_contents('somefile.txt'))