txt file into array with delimiters in php - php

My ips.txt file contains the following content:
radie1230: 116.79.254.131
Y_O_L_O: 122.149.157.42
midgetman63: 121.121.14.101, 124.112.115.69, 114.182.51.1, 114.118.55.131, 111.21.22.156
kypero: 121.211.61.118, 117.117.117.46, 121.214.109.247, 111.219.37.75
lythorous: 111.161.225.214, 12.111.184.71, 1.112.201.113, 11.137.214.184, 1.115.21.117, 12.115.241.212, 11.117.116.217
This list contains usernames on the left, separated by : from IPs on the right. IPs are separated by ,.
What would be an implementation to create the following output?
Array (
[midgetman63] => Array
(
[0] => 121.121.14.101
[1] => 124.112.115.69
[2] => 114.182.51.1
[3] => 114.118.55.131
[4] => 111.21.22.156
)
)

Try this:
$dataFromFile = file('ips.txt');
$dataFromFile = array_map('trim', $dataFromFile);
$result = array();
foreach ($dataFromFile as $line) {
list($user, $ips) = explode(':', $line, 2);
$arrayOfIPs = explode(',', $ips);
$result[trim($user)] = array_map('trim', $arrayOfIPs);
}
var_dump($result);

if you dont have spaces at the end of the textfile, this should be work.
good luck.
$text = file_get_contents("ipsontext.txt");
$array = explode("\n",$text);
$finally_array = array();
foreach ($array as $key => $value) {
$this_key = explode(":",$value);
$this_values = explode(",",$this_key[1]);
foreach($this_values as $tv) {
$finally_array[$this_key[0]][] = $tv;
}
}
var_dump($finally_array);

Maybe this?
<?php
$output = array();
$search = 'something';
$lines = file('file.txt');
foreach($lines as $line) {
if(strpos($line, $search) !== false) {
$d = explode(':', $line);
$s = explode(',', $d[1]);
foreach $s as $i { array_push($output, $i); }
}
}
print_r($output);
?>

Related

Formating a txt file

I have a TXT file formatting that looks like:
123451234512345
123451234512345
I want to format the file with php in this format:.
12345-12345-12345
12345-12345-12345
This is what I have tried:
$codes = "codes.txt";
$unformatedCode = file($codes, FILE_IGNORE_NEW_LINES);
$abcd = "-";
foreach ($array as $value) {
$text = (string)$unformatedCode;
$arr = str_split($text, "");
$formatedCode = implode("-", $arr);
echo $formatedCode;
}
Try this,
<?php
$arr = array_map(
fn($v) => implode('-', str_split($v, 5)),
file("codes.txt", FILE_IGNORE_NEW_LINES)
);
print_r($arr);
Result:
Array
(
[0] => 12345-12345-12345
[1] => 12345-12345-12345
)
If you want to echo the result then do <?= implode(PHP_EOL, $arr) ?>
Possible that if can be written shorter
$codes = "codes.txt";
$array = file($codes, FILE_IGNORE_NEW_LINES);
$p = "/([1-9]{5})([1-9]{5})([1-9]{5})/i";
$r = "${1}-${2}-${3}";
foreach ($array as $a) {
echo preg_replace($p, $r, $a);
}

Convert data generated by print_r() back to php code

I have text which is generated by print_r($some_array,true) and it looks something like this:
Array
(
[name] => Jon
[lastname] => Jonson
[car] => Array
(
[name] => bmw
[year] => 2012
)
)
(Real data have much more values and more dimensions.)
Question: how to convert this data back, into php's array ?
Looking at the print_r documentation on php.net 'Matt' has posted a solution:
<?php
function print_r_reverse($in) {
$lines = explode("\n", trim($in));
if (trim($lines[0]) != 'Array') {
// bottomed out to something that isn't an array
return $in;
} else {
// this is an array, lets parse it
if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
$spaces = $match[1];
$spaces_length = strlen($spaces);
$lines_total = count($lines);
for ($i = 0; $i < $lines_total; $i++) {
if (substr($lines[$i], 0, $spaces_length) == $spaces) {
$lines[$i] = substr($lines[$i], $spaces_length);
}
}
}
array_shift($lines); // Array
array_shift($lines); // (
array_pop($lines); // )
$in = implode("\n", $lines);
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
$pos = array();
$previous_key = '';
$in_length = strlen($in);
// store the following in $pos:
// array with key = key of the parsed array's item
// value = array(start position in $in, $end position in $in)
foreach ($matches as $match) {
$key = $match[1][0];
$start = $match[0][1] + strlen($match[0][0]);
$pos[$key] = array($start, $in_length);
if ($previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
$previous_key = $key;
}
$ret = array();
foreach ($pos as $key => $where) {
// recursively see if the parsed out value is an array too
$ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
}
return $ret;
}
}
?>
(Not my code)

string to associative array conversion

I've been struggling with this for a few days and wanted to throw it out there and see if someone has any ideas.
Basically I have a string e.g
1) "/0/bar"
2) "/build/0/foo/1"
and need to convert this into a multidimensional array
1) $result[0][bar]
2) $result[build][0][foo][1]
So far I've tried:
$query = "/build/0/foo/1";
$queryAr = [];
$current = &$queryAr;
$keys = explode("/", $query);
foreach($keys as $key) {
#$current = &$current[$key];
}
$current = $value;
quieting the output is a pretty hacky way to achive this...
You need to trim the first / of the string. live demo.
<?php
$query = "/build/0/foo/1";
$queryAr = [];
$current = &$queryAr;
$keys = explode("/", trim($query, '/'));
foreach($keys as $key) {
#$current = &$current[$key];
}
$current = $value;
print_r($queryAr);
I tried a recursive function version:
$query = "/build/0/foo/1";
print_r($result = buildNestedArray(explode('/', trim($query, '/'))));
function buildNestedArray($keys)
{
$k = current($keys);
$result = [$k => 'DONE'];
array_shift($keys);
if (sizeof($keys) > 0) { $result[$k] = buildNestedArray($keys); }
return $result;
}
output: Array ( [build] => Array ( [0] => Array ( [foo] => Array ( [1] => DONE ) ) ) )

Split an array by key

I have an array with the following keys:
Array
{
[vegetable_image] =>
[vegetable_name] =>
[vegetable_description] =>
[fruit_image] =>
[fruit_name] =>
[fruit_description] =>
}
and I would like to split them based on the prefix (vegetable_ and fruit_), is this possible?
Currently, I'm trying out array_chunk() but how do you store them into 2 separate arrays?
[vegetables] => Array { [vegetable_image] ... }
[fruits] => Array { [fruit_image] ... }
This should work for you:
$fruits = array();
$vegetables = array();
foreach($array as $k => $v) {
if(strpos($k,'fruit_') !== false)
$fruits[$k] = $v;
elseif(strpos($k,'vegetable_') !== false)
$vegetables[$k] = $v;
}
As an example see: http://ideone.com/uNi54B
Out of the Box
function splittArray($base_array, $to_split, $delimiter='_') {
$out = array();
foreach($to_split as $key) {
$search = $key.delimiter;
foreach($base_array as $ok=>$val) {
if(strpos($ok,$search)!==false) {
$out[$key][$ok] = $val;
}
}
return $out;
}
$new_array = splittArray($array,array('fruit','vegetable'));
It is possible with array_reduce()
$array = ['foo_bar' => 1, 'foo_baz' => 2, 'bar_fee' => 6, 'bar_feo' => 9, 'baz_bee' => 7];
$delimiter = '_';
$result = array_reduce(array_keys($array), function ($current, $key) use ($delimiter) {
$splitKey = explode($delimiter, $key);
$current[$splitKey[0]][] = $key;
return $current;
}, []);
Check the fiddle
Only one thins remains: you are using different forms (like "vegetable_*" -> "vegetables"). PHP is not smart enough to substitute language (that would be English language in this case) transformations like that. But if you like, you may create array of valid forms for that.
Use explode()
$arrVeg = array();
$arrFruit = array();
$finalArr = array();
foreach($array as $k => $v){
$explK = explode('_',$k);
if($explK[0] == 'vegetable'){
$arrVeg[$k] = $v;
} elseif($explK[0] == 'fruit') {
$arrFruit[$k] = $v;
}
}
$finalArr['vegetables'] = $arrVeg;
$finalArr['fruits'] = $arrFruit;
Use simple PHP array traversing and substr() function.
<?php
$arr = array();
$arr['vegetable_image'] = 'vegetable_image';
$arr['vegetable_name'] = 'vegetable_name';
$arr['vegetable_description'] = 'vegetable_description';
$arr['fruit_image'] = 'fruit_image';
$arr['fruit_name'] = 'fruit_name';
$arr['fruit_description'] = 'fruit_description';
$fruits = array();
$vegetables = array();
foreach ($arr as $k => $v) {
if (substr($k, 0, 10) == 'vegetable_') {
$vagetables[$k] = $v;
}
else if (substr($k, 0, 6) == 'fruit_') {
$fruits[$k] = $v;
}
}
print_r($fruits);
print_r($vagetables);
Working Example

how to explode a string and make an echo of a chosen attribute

I have a string containing ; subdivided by , and would like to make an echo of a chosen value.
My string is $string='Width,10;Height,5;Size,1,2,3'
I want to make an echo of the Height value (echo result must be 5)
$parts = explode(';', $string);
$component = explode(',', $parts[1]); // [1] is the Height,5 portion
echo $component[1]; // 5
Or this:
$p = explode(';', $string);
$data = array();
foreach($p as $part) {
$split = explode(',',$part,2); //the 'Size' bit different that the rest. I assume 1,2,3 is the value for Size?
$data[$split[0]] = $split[1];
}
$what_you_want_to_find = 'Height';
echo $data[$what_you_want_to_find];
try this:
$attrs = explode(";", $string);
$attrHeight = "";
foreach ($attrs as $value) {
if (strpos($value, "Height") !== false)
$attrHeight = explode(",", $value);
}
echo $attrHeight;

Categories