how to get string in among of lines using php - php

I am having a file like settings.txt.
which contains some lines like
SET VERSION=3
SET BACKUP_DRIVE=D:\
SET BACKUP_DIRECTORY=BACKUP\
SET HOURLY_DIRECTORY=HOURLY\
SET INPUT_DIRECTORY=C:\MySQL\Data\CDR\
SET username=username
SET password=password
this file is at other location or on other server. I have get this file using ...
$frserver = file_get_contents("http://ip is here/cdr/settings.txt");
I used this
$File = file_get_contents("http://ip is heresettings.txt");
$FileArr = explode("\r\n",$File);
echo $FileArr[5]; // This will output: SET username=desired username
and get "SET username=desired username" bt i want only "desired username"..just this issue left nw
Now I am unable to get username and password from it.
how to get username and password so i can compare them in db...

Assuming
$frserver = 'SET VERSION=3
SET BACKUP_DRIVE=D:\
SET BACKUP_DIRECTORY=BACKUP\
SET HOURLY_DIRECTORY=HOURLY\
SET INPUT_DIRECTORY=C:\MySQL\Data\CDR\
SET username=username
SET password=password';
the whole solution is just these 2 lines:
preg_match_all('~^SET\s+([^=]+)=(.*)$~m', $frserver, $matches);
$params = array_combine($matches[1], $matches[2]);
So after that you can retrieve your variables as $params['username'] and $params['password'] correspondingly.
Live example on ideone: http://ideone.com/pn2Wbp

$File = file_get_contents("Settings.txt");
$FileArr = explode("\r\n",$File);
echo $FileArr[5]; // This will output: SET username=username
Explained:
This code will break up the contents of the file specified by new line breaks represented by \r\n which is the windows format for new line.. HTML equivalent: <br>
To See the full array:
print_r($FileArr);

If you just need to get data from a text file, I recommend using a csv, like this:
key,value
VERSION,3
BACKUP_DRIVE,D:\
BACKUP_DIRECTORY,BACKUP\
HOURLY_DIRECTORY,HOURLY\
INPUT_DIRECTORY,C:\MySQL\Data\CDR\
username,username
password,password
Then you can do something like this to get all these keys and values into a PHP array:
$contents = file_get_contents('http://ip is here/cdr/settings.txt');
$lines = explode("\n",$contents);
foreach($lines as $line) {
$pair = str_getcsv($line);
$settings[] = array($pair[0]=>$pair[1]);
}
// print_r to see the array
print_r($settings);

You are probably best served using file() to fetch the data, such that the data returned is in an array already (one element per line of text):
$raw_array = file('http://ip is here/cdr/settings.txt');
Then perhaps run an array walk to set everything to a usable array
$final_array = array();
array_walk($raw_array, function($value) use $final_array {
$value = trim($value); // trim newlines
$value = str_replace('SET ', '', $value); // remove 'SET '
$value_array = explode('=', $value); // break up value on '='
$final_array[$value_array[0]] = $value_array[1]; // set key/value in $final_array
});
For PHP version < 5.3 where there is not support for anonymous functions, you need to use a named function here, so it might look like this:
$final_array = array();
array_walk($raw_array, 'parse_raw_array', $final_array);
function parse_raw_array ($value, $key_not_used, $final_array) {
$value = trim($value); // trim newlines
$value = str_replace('SET ', '', $value); // remove 'SET '
$value_array = explode('=', $value); // break up value on '='
$final_array[$value_array[0]] = $value_array[1]; // set key/value in $final_array
});
Then simply access key/values from $final_array as needed
$username = $final_array['username'];
$password = $final_array['password'];
That being said, passing your MySQL credentials (I assume that is what this is) in the clear like that is probably not a great idea.

Related

How to convert comma separated key value string to associative array in PHP

I tried searching for a quick fix to converting a comma separated key=>value string to an associative array but couldn't find any. So i had to make a quick fix myself.
ANTECEDENT
I generated an array of some form elements using Jquery, to be sent via ajax.
So I have something like:
var myarray = [];
var string1 = 'key1=>'+form['value1'].value; //and we have string2 and more
myarray.push(string1);
Then i sent "myarray" as data to the form handling script.
PROBLEM
Now i have an array to deal with in my php script. I have the following:
function($var,$data){
$string = $data('myarray'); //array created earlier with jquery
}
Which is the same as:
...
$string = array(0=>'key1=>value1',1=>'key2=>value2');
...
Meanwhle, what i need is:
...
$string = array('key1'=>'value1','key2'=>'value2');
...
SOLUTION
...
$string = $data('myarray');
$string1 = array();
foreach($string as $value){
$split = explode('=>',$value);
$string1[$split[0]]=$split[1];
}
...
Now i can access the value of each key as:
echo $string1['key1']; //gives value1
This solution can also be used in a situation where you have:
$string = 'key1=>value1,key2=>value2...';
$string = explode(',',$string); // same as $string = array('key1'=>'value1',...)
$string1 = array();
foreach($string as $value){
$split = explode('=>',$value);
$string1[$split[0]]=$split[1];
}
The solution is rather simpler than i expected but if you know a better way to make this kind of conversion, feel free to suggest.
You can add as key value pair in javascript. Then you don't need to do any operations, can access directly in PHP.
var myarray = {};
myarray['key1'] = form['value1'].value;
In PHP :
$arr = $data('myarray');
echo $arr['key1']
Use explode() to split up the string.
$string = 'key1=>value1,key2=>value2,key3=>value3';
$pairs = explode(',', $string);
$data = array();
foreach ($pairs as $pair) {
list($key, $value) = explode('=>', $pair);
$data[$key] = $value;
}
var_dump($data);
DEMO

How can I check if a username already exists in a file and also add his points to him?

I intentionally want to use a text file to do this. So I read a text file and I want to check if a username already exists in that text file or not and I want to either add this username to the text file if he doesn't exists or just add the points to him.
My current code:
<?php
$myfile = fopen("test.txt", "r") or die("Unable to open file!");
$file = fread($myfile,filesize("test.txt"));
//echo $file;
fclose($myfile);
//$username = $_REQUEST['username'];
//$points = $_REQUEST['point'];
$username = 'chinmay'; //chinmay is a username this is unique
$points = 200; //if username chinmay not exitst then Insert first time otherwise if username chimay exist then next onwards this point will update everytime in the text file.
$myfileWrite = fopen("test.txt", "a") or die("Unable to open file!");
$txt = $username."|".$points."\n";
fwrite($myfileWrite, $txt);
fclose($myfileWrite);
?>
test.txt:
chinmay|800
john|200
sanjib|480
debasish|541
This is my complete code. My requirement is:
\n is not working when I am using this text inserted in the same line.
How can I check duplicate username?
If I found username then how can I update user points?
I googled last 2 hours but not getting any solution. I have no idea about this problem.
This should work for you:
First use file() to read your file into an array. Then you can use array_map() to loop through each line and explode() it by | as delimiter. After this you can use array_column() to get the username as key for the points as value. Like this:
Array
(
[chinmay] => 1200
[john] => 200
[sanjib] => 480
[debasish] => 541
[chinmayx] => 200
)
With the array you can simply check if the username already exists or not. If not add it to the array and then add the points to it.
After adding the points to the username you can change your data back in the same format and save it with file_put_contents().
Full code:
<?php
$lines = file("test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$usernames = array_column(array_map(function($v){
return explode("|", $v);
}, $lines), 1, 0);
$username = "chinmayx";
$points = 200;
if(!isset($usernames[$username]))
$usernames[$username] = 0;
$usernames[$username] += $points;
foreach($usernames as $k => $v)
$data[] = "$k|$v" . PHP_EOL;
file_put_contents("test.txt", $data);
?>
EDIT:
If you have PHP under 5.5 just replace:
$usernames = array_column(array_map(function($v){
return explode("|", $v);
}, $lines), 1, 0);
with this:
$lines = array_map(function($v){
return explode("|", $v);
}, $lines);
$usernames = array_combine(
array_map(function($v){
return $v[0];
}, $lines),
array_map(function($v){
return $v[1];
}, $lines)
);
Also if you want to get the TOP 10 users, just rsort() your array and then take an array_slice() of the first 10 elements, e.g.
rsort($usernames);
$topUsers = array_slice($usernames, 0, 10);
print_r($topUsers);
To get the \n working use the PHP_EOL as in another answer
$txt = $username."|".$points.PHP_EOL;
To update the user found in the text file go through following link
how to replace a particular line in a text file using php?
you should use PHP_EOL instead of "\n" which also depends on your OS
$txt = $username."|".$points.PHP_EOL;
for checking userName, just use:
//this works because $file is String because of fread()
if (strpos($file,$username) !== false) {
echo 'user exists';
}
for replacing you'll need regex or use strpos position (which returns position of name in string) and advance the pointer by count($username)+1 and search from there for newline, all this string between that, replace with new points
Try to use preg_match:
$file = fopen("score.txt", "r");
while (!feof($file)) {
preg_match("/^$username|(.*?)$/", $file, $array);
var_dump($array);
}
but I think it's better to use MySQL :)

multi-dimensional array possibly

I have two files that I need opened, I'm using php file to read them
$lines = file('/home/program/prog_conf.txt');
foreach ($lines as $line) {
$rows = preg_split('/\s+/', $line);
Followed by:
$lines = file('/home/domain/public_html/base/file2.cfg');
foreach ($lines as $line) {
$rows = preg_split('/=/', $line);
As I work with these two files, I need to pull info from the second one, which I seperated by =, however, I'm not sure this is the best thing to do. I wanted to add data checking from the database. The db details are in the second file like so:
dbname = databasename
dbuser = databaseuser
dbpass = databasepassword
If I echo the $rows[2], I get everything all the information I need on a single line, not on seperate lines. Meaning:
databasename databaseuser databasepassword
How do I split the information up so I can use the entries one by one?
How about:
$lines = file('/home/domain/public_html/base/file2.cfg');
$all_parts = array()
foreach ($lines as $line) {
//explode pulls apart a string based on the first value, so you could change that
//to a '=' if need be
array_merge($all_parts,explode(' ', $line));
}
This would get you all the parts of the file, one at a time, into an array. Which is what I think you wanted.
If not, just explode as needed
Maybe this aproach helps:
First as i see your second file has multiple lines, so what would do is something like this:
Assumin that every key as "db" in common we can do something like this.
$file = fopen("/home/domain/public_html/base/file2.cfg", "rb");
$contents = stream_get_contents($handle); // This function return better performance if the file isn't too large.
fclose($file);
// Assuming this is your return from the file
$contents = 'dbname = databasename dbuser = databaseuser dbpass = databasepassword';
$rows = preg_split('/db+/', $contents); // Splinting keys "db"
$result = array();
foreach($rows as $row){
$temp = preg_replace("/\s+/", '', $row); // Removing extract white spaces
$temp = preg_split("/=/", $temp); // Splinting by "="
$result[] = $temp[1]; // Getting the value only
}
var_dump ($result);
I hope this help you can try this code maybe with little modifications but works.

Parsing a formatted text file in PHP

Is there an easy way to parse the following data that I will post below. The data comes from the web.
I was using the $rows = explode("\n", $txt_file); then the $parts = explode('=', $line_of_text); to get the key name and values. However, I don't know how to handle the extra information that I do not want.
Additionally, I do not know how to get rid of the extra spaces. The file seems to be made for some kind of easy parsing. I have looked all over this site to find a solution. However, this data is quite different than the examples I have found on this site.
# This file holds all the timelines available at this time.
# All lines starting with # is ignored by parser...
#
STARTINFO
description = Rubi-Ka 2
displayname = Rimor (Rubi-Ka 2)
connect = cm.d2.funcom.com
ports = 7502
url =
version = 18.5.4
ENDINFO
STARTINFO
description = Rubi-Ka 1
displayname = Atlantean (Rubi-Ka 1)
connect = cm.d1.funcom.com
ports = 7501
url =
version = 18.5.4
ENDINFO
You can use the trim function to get rid of the whitespace.
To only keep the columns you want, you can store their keys in an array, and make a check against it when parsing.
Here's an example (albeit rather verbose).
<?
$lines = explode("\n", $data);
$result = array();
$count = 0;
// an array of the keys we want to keep
// I have the columns as keys rather then values for faster lookup
$cols_to_keep = array( 'url'=>null, 'description'=>null, 'ports'=>null, 'displayname' => null);
foreach($lines as $line)
{
//skip comments and empty lines
if(empty($line) || $line[0] == '#')
{ continue; }
//if we start a new block, initalize result array for it
if(trim($line) == 'STARTINFO')
{
$result[$count] = array();
continue;
}
// if we reach ENDINFO increment count
if(trim($line) == 'ENDINFO')
{
$count++;
continue;
}
//here we can split into key - value
$parts = explode('=', $line);
//and if it's in our cols_to_keep, we add it on
if(array_key_exists(trim($parts[0]), $cols_to_keep))
{ $result[$count][ trim($parts[0]) ] = trim( $parts[1] ); }
}
print_r($result);
?>

Be sure to have unique array entry

I have a file which contains something like :
toto;145
titi;7
tata;28
I explode this file to have an array.
I am able to display the data with that code :
foreach ($lines as $line_num => $line) {
$tab = explode(";",$line);
//erase return line
$tab[1]=preg_replace('/[\r\n]+/', "", $tab[1]);
echo $tab[0]; //toto //titi //tata
echo $tab[1]; //145 //7 //28
}
I want to be sure that data contained in each $tab[0] and $tab[1] is unique.
For example, I want a "throw new Exception" if file is like :
toto;145
titi;7
tutu;7
tata;28
or like :
toto;145
tata;7
tata;28
How can I do that ?
Convert your file to array with file(), and convert to associative array with additional duplication checking.
$lines = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$tab = array();
foreach ($lines as $line) {
list($key, $val) = explode(';', $line);
if (array_key_exists($key, $tab) || in_array($val, $tab)) {
// throw exception
} else {
$tab[$key] = $val;
}
}
Store them as key => value pairs in an array, and check whether each key or value already exists in your array as you are looping through the file. You can check for an existing key with array_key_exists and an existing value with in_array.
One simple is using array_unique, save the parts (tab[0] and tab[1]) into two separate arrays after you explode, name them for example $col1 and $col2 and then, you could do this simple test:
<?php
if (count(array_unique($col1)) != count($col1))
echo "arrays are different; not unique";
?>
PHP will turn your array parts into unique, if duplicated entrys exist, so if the size of the new array differs from the original, it means that it was not unique.
//contrived file contents
$file_contents = "
toto;145
titi;7
tutu;7
tata;28";
//split into lines and set up some left/right value trackers
$lines = preg_split('/\n/', trim($file_contents));
$left = $right = array();
//split each line into two parts and log left and right part
foreach($lines as $line) {
$splitter = explode(';', preg_replace('/\r\n/', '', $line));
array_push($left, $splitter[0]);
array_push($right, $splitter[1]);
}
//sanitise left and right parts into just unique entries
$left = array_unique($left);
$right = array_unique($right);
//if we end up with fewer left or right entries than the number of lines, error...
if (count($left) < count($lines) || count($right) < count($lines))
die('error');
Use associative arrays with keys "toto", "tata" etc.
To check whether a key exists you can use array_key_exists or isset.
BTW. Instead of preg_replace('/[\r\n]+/', "", $tab[1]), try trim (or even rtrim).
While you're traversing the array add the values to an existing array, i.e. placeholder, which will be used to check if the value exists or not via in_array().
<?php
$lines = 'toto;145 titi;7 tutu;7 tata;28';
$results = array();
foreach ($lines as $line_num => $line) {
$tab = explode(";",$line);
//erase return line
$tab[1]=preg_replace('/[\r\n]+/', "", $tab[1]);
if(!in_array($tab[0]) && !in_array($tab[1])){
array_push($results, $tab[0], $tab[1]);
}else{
echo "value exists!";
die(); // Remove/modify for different exception handling
}
}
?>

Categories