I have a text file countries.txt with a list of all countries:
1. Australia
2. Austria
3. Belgium
4. US
I want to create an array in country_handler.php like this:
$countries = array(
'1'=>'Australia',
'2'=>'Austria',
'3'=>'Belgium',
'4'=>'US'
);
How to do that?
Better you can use this in a function like below - then just called this function from any where
function getCountryList()
{
return array(
'1'=>'Australia',
'2'=>'Austria',
'3'=>'Belgium',
'4'=>'US'
);
}
$data = file_get_contents('countries.txt');
$countries = explode(PHP_EOL, $data);
$file = file('countries.txt');
$countries = array();
foreach ($file as $line) {
#list ($index, $country) = explode('.', $line);
$countries[trim($index)] = trim($country);
}
print_r($countries);
$lines = file('countries.txt');
$newArr = array();
foreach ($lines as $line) {
$erg = preg_split('/\.\s+/', $line);
$newArr[$erg[0]] = $erg[1];
}
var_dump($newArr);
Luckily (sometimes) regex doesn't include newlines in the ., so you can do this:
$contents = file_get_contents('countries.txt');
preg_match_all('#(\d+)\.\s+(.+)#', $contents, $matches);
print_r($matches);
The regex means:
(\d+) -- a number (save this)
\. -- a literal dot
\s+ -- white space
(.+) -- any character except \n or \r (end-of-line) (save this)
Which results in:
Array
(
[0] => Array
(
[0] => 1. Australia
[1] => 2. Austria
[2] => 3. Belgium
[3] => 4. US
)
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[2] => Array
(
[0] => Australia
[1] => Austria
[2] => Belgium
[3] => US
)
)
and I'm sure from [1] and [2] you can make the keyed array you need.
array_combine to the easy rescue:
$countries = array_combine($matches[1], $matches[2]);
Try this:
<?php
$data = file_get_contents('countries.txt');
$countries = explode(PHP_EOL,$data);
$cnt = 1;
foreach($countries as $val) {
if($val <>"") {
$res[$cnt] = strstr(trim($val), ' ');
$cnt++;
}
}
print_r($res);
?>
Related
Hi I have been doing this project for almost a month now. Is there's anyway I can store the value of the next string after the searched string in the list of array?
For example:
Deviceid.txt content is:
Created:21/07/2016 1:50:53; Lat:30.037853; Lng:31.113798; Altitude:79; Speed:0; Course:338; Type:Gps;
Created:21/07/2016 1:49:53; Lat:30.037863; Lng:31.113733; Altitude:60; Speed:0; Course:338; Type:Gps;
Here is my sample php coding
$file_handle = fopen("data/deviceid.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
array_push($a,$line);
}
$searchword = 'Lat';
$matches = array_filter($a, function($var) use ($searchword) {
return preg_match("/\b$searchword\b/i", $var);
});
print_r($matches);
fclose($file_handle);
Matches Data:
[0] = 30.037853
[1] = 30.037863
After parsing the file with the code below, you can use array_column (php v5.5.0+) to get all values from a specific key, like so:
array_column($parsed, 'Lat');
Output:
Array
(
[0] => 30.037853
[1] => 30.037863
)
See it in action here.
And here is the code to parse the content of the file:
// $a = each line of the file, just like you're doing
$a = array_filter($a); // remove empty lines
$parsed = array();
foreach($a as $v1){
$a1 = explode(';', $v1);
$tmp = array();
foreach($a1 as $v2){
$t2 = explode(':', $v2);
if(count($t2) > 1){
$tmp[trim(array_shift($t2))] = trim( implode(':', $t2) );
}
}
$parsed[] = $tmp;
}
This is the structure of $parsed:
Array
(
[0] => Array
(
[Created] => 21/07/2016 1:50:53
[Lat] => 30.037853
[Lng] => 31.113798
[Altitude] => 79
[Speed] => 0
[Course] => 338
[Type] => Gps
)
[1] => Array
(
[Created] => 21/07/2016 1:49:53
[Lat] => 30.037863
[Lng] => 31.113733
[Altitude] => 60
[Speed] => 0
[Course] => 338
[Type] => Gps
)
)
See the code in action here.
I wrote a quick regex that can help you pull the field names and values from each line.
You may try with this:
$re = "/((?P<fieldname>[^\\:]*)\\:(?P<fieldvalue>[^\\;]*); *)/";
$str = "Created:21/07/2016 1:50:53; Lat:30.037853; Lng:31.113798; Altitude:79; Speed:0; Course:338; Type:Gps;";
preg_match_all($re, $str, $matches);
Do a print_r of $matches to inspect the results.
Hope this helps.
After your array_filter, iterate through your matches and apply a more specific regex to each line:
$lats = array();
foreach ($matches as $line)
{
$match = array();
preg_match("/\b$searchword:([\d\.]+);/i", $var, $match);
$lats[] = $match[1];
}
print_r($lats);
The variable $match will be populated with the full regex match at index 0, and the parenthesized match at index 1.
I have a text file which I must read, and use the data from.
3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry
How can I create an array of these strings in the following form?
array(
"name" => "number"
...
)
I tried this:
$handle = fopen("file.txt", "r");
fscanf($handle, "%d %d", $name, $number);
What then? No matter what I try, it only works for the first line.
sam 99912222
Added codes to have both types of output - ignoring and including the lines that don't have name-value pairs. Check them out below
This code goes through each line and gets only the ones that have both name and value (something[space]something)):
//$lines = ... each line of the file in an array
$vals = array();
foreach($lines as $v){
$tmp = explode(' ', $v);
if(count($tmp) > 1){
$vals[trim($tmp[0])] = trim($tmp[1]); // trim to prevent garbage
}
}
print_r($vals);
It will output this:
Array
(
[sam] => 99912222
[tom] => 11122222
[harry] => 12299933
)
See the code in action here.
If you need the values even if they didn't come in pairs, do it like this:
//$lines = ... each line of the file
$vals = array();
foreach($lines as $v){
$tmp = explode(' ', $v);
$name = '';
$number = '';
$tmp[0] = trim($tmp[0]);
if(count($tmp) > 1){
$name = $tmp[0];
$number = trim($tmp[1]);
}else{
if(is_numeric($tmp[0])){
$number = $tmp[0];
}else{
$name = $tmp[0];
}
}
$vals[] = array(
'name' => $name,
'number' => $number
);
}
print_r($vals);
And the output:
Array
(
[0] => Array
(
[name] =>
[number] => 3
)
[1] => Array
(
[name] => sam
[number] => 99912222
)
[2] => Array
(
[name] => tom
[number] => 11122222
)
[3] => Array
(
[name] => harry
[number] => 12299933
)
[4] => Array
(
[name] => sam
[number] =>
)
[5] => Array
(
[name] => edward
[number] =>
)
[6] => Array
(
[name] => harry
[number] =>
)
See the code in action here.
Data in file are inconsistent, best of is to use regex to identify what data you've got from each line.
$lines = file('file.txt'); // this will open file and split them into lines
$items = array();
foreach($lines as $line){
$name = null;
$number = null;
$nameFound = preg_match("|([A-Za-z]+)|", $line, $matches);
if($nameFound){
$name = $matches[0];
}
$numberFound = preg_match("|([0-9]+)|", $line, $matches);
if($numberFound){
$number = $matches[0];
}
$items[] = array('name' => $name, 'number' => $number);
}
Then in items you should find parsed data from file.
To make it just extract full format data just change lines with regex into one line like this:
$lines = file('file.txt'); // this will open file and split them into lines
$items = array();
foreach($lines as $line){
$userFound = preg_match("/([A-Za-z]+) ([0-9]+)/", $line, $matches);
if($userFound){
$items[$matches[1]] = $matches[2];
}
}
With the Algorithm below, you can simply parse each individual line of the Text-File Contents into an array with the 1st Word or Digit(s) on each line as the Key and the 2nd Word as the Value. When the 2nd word or group of words do not exist, a NULL is assigned to that Key. For re-usability, this algorithm has been encapsulated into a Function. Here you go:
<?php
function parseTxtFile($txtFile){
$arrTxtContent = [];
if(!file_exists($txtFile)){ return null;}
$strFWriteTxtData = file_get_contents($txtFile);
if(empty($strFWriteTxtData)){return null;}
$arrFWriteInfo = explode("\n", $strFWriteTxtData);
foreach($arrFWriteInfo as $iKey=>$lineData){
$arrWriteData = explode(", ", $lineData);
foreach($arrWriteData as $intKey=>$strKeyInfo){
preg_match("#(^[a-z0-9_A-Z]*)(\s)(.*$)#i", $strKeyInfo, $matches);
preg_match("#(^[a-z0-9_A-Z]*)(\s*)?$#i", $strKeyInfo, $matches2);
if($matches) {
list(, $key, $null, $val) = $matches;
if (!array_key_exists($key, $arrTxtContent)) {
$arrTxtContent[$key] = $val;
}else{
$iKey = $intKey + 1;
$key = $key . "_{$iKey}";
$arrTxtContent[$key] = $val;
}
}else if($matches2) {
list(, $key, $null) = $matches2;
if (!array_key_exists($key, $arrTxtContent)) {
$arrTxtContent[$key] = null;
}else{
$key = preg_match("#_\d+#", $key, $match)? $key . $match[0] : "{$key}_1";
$arrTxtContent[$key] = null;
}
}
}
}
return $arrTxtContent;
}
var_dump(parseTxtFile(__DIR__ . "/data.txt"));
Just call the function parseTxtFile($txtFile) passing it the path to your text File and it will return an Array that looks something like below:
array (size=7)
3 => null
'sam' => string '99912222' (length=8)
'tom' => string '11122222' (length=8)
'harry' => string '12299933' (length=8)
'sam_1' => null
'edward' => null
'harry_1' => null
Hope this could help a bit....
Cheers & Good-Luck ;-)
I have this file format of txt file generated from schematic software:
(
NETR5_2
R6,1
R5,2
)
(
NETR1_2
R4,2
R3,1
R3,2
R2,1
R2,2
R1,1
R1,2
)
I need to get this:
Array
(
[0] => Array
(
[0] => NETR5_2
[1] => R6,1
[2] => R5,2
)
[1] => Array
[0] => NETR1_2
[1] => R4,2
[2] => R3,1
[3] => R3,2
[4] => R2,1
[5] => R2,2
[6] => R1,1
[7] => R1,2
)
Here is code i try but i get all from input string:
$file = file('tangoLista.txt');
/* GET - num of lines */
$f = fopen('tangoLista.txt', 'rb');
$lines = 0;
while (!feof($f)) {
$lines += substr_count(fread($f, 8192), "\n");
}
fclose($f);
for ($i=0;$i<=$lines;$i++) {
/* RESISTORS - check */
if (strpos($file[$i-1], '(') !== false && strpos($file[$i], 'NETR') !== false) {
/* GET - id */
for($k=0;$k<=10;$k++) {
if (strpos($file[$i+$k], ')') !== false || empty($file[$i+$k])) {
} else {
$json .= $k.' => '.$file[$i+$k];
}
}
$resistors_netlist[] = array($json);
}
}
echo '<pre>';
print_r($resistors_netlist);
echo '</pre>';
I need to read between ( and ) and put into array values...i try using checking if line begins with ( and NETR and if yes put into array...but i don't know how to get number if items between ( and ) to get foreach loop to read values and put into array.
Where i im making mistake? Can code be shorter?
Try this approach:
<?php
$f = fopen('test.txt', 'rb');
$resistors_netlist = array();
$current_index = 0;
while (!feof($f)) {
$line = trim(fgets($f));
if (empty($line)) {
continue;
}
if (strpos($line, '(') !== false) {
$resistors_netlist[$current_index] = array();
continue;
}
if (strpos($line, ')') !== false) {
$current_index++;
continue;
}
array_push($resistors_netlist[$current_index], $line);
}
fclose($f);
print_r($resistors_netlist);
This gives me:
Array
(
[0] => Array
(
[0] => NETR5_2
[1] => R6,1
[2] => R5,2
)
[1] => Array
(
[0] => NETR1_2
[1] => R4,2
[2] => R3,1
[3] => R3,2
[4] => R2,1
[5] => R2,2
[6] => R1,1
[7] => R1,2
)
)
We start $current_index at 0. When we see a (, we create a new sub-array at $resistors_netlist[$current_index]. When we see a ), we increment $current_index by 1. For any other line, we just append it to the end of $resistors_netlist[$current_index].
Try this, using preg_match_all:
$text = '(
NETR5_2
R6,1
R5,2
)
(
NETR1_2
R4,2
R3,1
R3,2
R2,1
R2,2
R1,1
R1,2
)';
$chunks = explode(")(", preg_replace('/\)\W+\(/m', ')(', $text));
$result = array();
$pattern = '{([A-z0-9,]+)}';
foreach ($chunks as $row) {
preg_match_all($pattern, $row, $matches);
$result[] = $matches[1];
}
print_r($result);
3v4l.org demo
I'm not the king of regex, so you can find a better way.
The main problem are parenthesis: I don't know what are between closing and next open parenthesis ( )????( ), so first I replace every space, tab, cr or ln between, then I explode the string by )(.
I perform a foreach loop for every element of resulted array, matching every occurrence of A-z0-9, and add array of retrieved values to an empty array that, at end of foreach, will contain desired result.
Please note:
The main pattern is based on provided example: if the values contains other characters then A-z 0-9 , the regex fails.
Edit:
Replaced preliminar regex pattern with `/\)\W+\(/m`
I have some searsh results like this
$search = 'an';
and some string that has many text like this
$text = 'Anda goes wiwsh totot anaana here goes like this <p>helle</p><b>an</b>Kako isyaay an koliko ana an here <div>hello ana</div>';
You will see there are a lots of words that have an
I need to go in that string and find only word that contained the search results and put in array, of course i dont need html inside, my final array must look like this
$results = array ('Anda','anaana','an','an','ana','an','ana');
Try something like this:
$all_words = explode(' ', strip_tags($text));
$results = array();
foreach ($all_words as $word) {
if (substr($search, $word) !== FALSE) {
$results[] = $word;
}
}
Note that because of the way your text is formatted, the array will include 'helleanKako' rather than 'an' in that one case.
Strrchr can return true when found match character,...
<?php
$search = "an";
$text = 'Anda goes wiwsh totot anaana here goes like this <p>helle</p><b>an</b>Kako isyaay an koliko ana an here <div>hello ana</div>';
$all_words = explode(' ', $text);
$results = array();
foreach ($all_words as $word) {
if (strrchr($word,$search) == TRUE) {
$results[] = $word;
}
}
var_dump($results);
?>
If it's not too late... :
<?php
$input = 'Anda goes wiwsh totot anaana here goes like this <p>helle</p><b>an</b>Kako isyaay an koliko ana an here <div>hello ana</div>';
$pattern = '/([^\s^>]*an[^\s^<]*)/i';
if (preg_match_all($pattern, $input, $matches)){
print_r($matches);
}
?>
Array
(
[0] => Array
(
[0] => Anda
[1] => anaana
[2] => an
[3] => an
[4] => ana
[5] => an
[6] => ana
)
[1] => Array
(
[0] => Anda
[1] => anaana
[2] => an
[3] => an
[4] => ana
[5] => an
[6] => ana
)
)
Hope that's what you've expected
I need to split this kind of strings to separate the email between less and greater than < >. Im trying with the next regex and preg_split, but I does not works.
"email1#domain.com" <email1#domain.com>
News <news#e.domain.com>
Some Stuff <email-noreply#somestuff.com>
The expected result will be:
Array
(
[0] => "email1#domain.com"
[1] => email#email.com
)
Array
(
[0] => News
[1] => news#e.domain.com
)
Array
(
[0] => Some Stuff
[1] => email-noreply#somestuff.com
)
Code that I am using now:
foreach ($emails as $email)
{
$pattern = '/<(.*?)>/';
$result = preg_split($pattern, $email);
print_r($result);
}
You may use some of the flags available for preg_split: PREG_SPLIT_DELIM_CAPTURE and PREG_SPLIT_NO_EMPTY.
$emails = array('"email1#domain.com" <email1#domain.com>', 'News <news#e.domain.com>', 'Some Stuff <email-noreply#somestuff.com>');
foreach ($emails as $email)
{
$pattern = '/<(.*?)>/';
$result = preg_split($pattern, $email, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($result);
}
This outputs what you expect:
Array
(
[0] => "email1#domain.com"
[1] => email1#domain.com
)
Array
(
[0] => News
[1] => news#e.domain.com
)
Array
(
[0] => Some Stuff
[1] => email-noreply#somestuff.com
)
Splitting on something removes the delimiter (i.e. everything the regex matches). You probably want to split on
\s*<|>
instead. Or you can use preg_match with the regex
^(.*?)\s*<([^>]+)>
and use the first and second capturing groups.
This will do the job. click here for Codepad link
$header = '"email1#domain.com" <email1#domain.com>
News <news#e.domain.com>
Some Stuff <email-noreply#somestuff.com>';
$result = array();
preg_match_all('!(.*?)\s+<\s*(.*?)\s*>!', $header, $result);
$formatted = array();
for ($i=0; $i<count($result[0]); $i++) {
$formatted[] = array(
'name' => $result[1][$i],
'email' => $result[2][$i],
);
}
print_r($formatted);
preg_match_all("/<(.*?)>/", $string, $result_array);
print_r($result_array);
$email='"email1#domain.com" <email1#domain.com>
News <news#e.domain.com>
Some Stuff <email-noreply#somestuff.com>';
$pattern = '![^\>\<]+!';
preg_match_all($pattern, $email,$match);
print_r($match);
Ouput:
Array ( [0] => Array (
[0] => "email1#domain.com"
[1] => email1#domain.com
[2] => News
[3] => news#e.domain.com
[4] => Some Stuff
[5] => email-noreply#somestuff.com ) )
You can also split by <, and get rid of ">" in $result
$pattern = '/</';
$result = preg_split($pattern, $email);
$result = preg_replace("/>/", "", $result);