Converting a string into an array of fixed length - php

I have a string that I want to convert into an array of 6 elements.
$x=Address : "MK/LK G8, 2ND FLR, MALAL VISO INFO 19-Aug-15 Acct Number : _254566003 etc...
IF I want an array
$parts[0]=MK/LKG......Length should be 6 (whitespace wont consider)
$parts[1]=82NDFLRLength should be 6
$parts[2]=etc.....

try this to split strings to array
$str = "MK/LK G8, 2ND FLR, MALAL VISO INFO 19-Aug-15 Acct Number : _254566003 etc..."
$arr = str_split($str, 6);

Simply use str_split along with the preg_replace as
$x="MK/LK G8, 2ND FLR, MALAL VISO INFO 19-Aug-15 Acct Number : _254566003 etc..";
$res = str_split(preg_replace('/\s/','',$x),6);
print_r($res);
Output:
Array
(
[0] => MK/LKG
[1] => 8,2NDF
[2] => LR,MAL
[3] => ALVISO
[4] => INFO19
[5] => -Aug-1
[6] => 5AcctN
[7] => umber:
[8] => _25456
[9] => 6003et
[10] => c..
)
Demo

Related

How to extract certain words from a php string?

I have a long string like this I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];. Now I just want to get certain words like 'I1','I2','I8','NA1' and so on i.e. words between ':'&';' only ,and store them in array. How to do that efficiently?
I have already tried using preg_split() and it works but giving me wrong output. As shown below.
// $a is the string I want to extract words from
$str = preg_split("/[;:]/", $a);
print_r($str);
The output I am getting is this
Array
(
[0] => I8
[1] => 2
[2] => I1
[3] => 1
[4] => I2
[5] => 2
[6] => I3
[7] => 2
[8] => I4
[9] => 4
[10] =>
)
Array
(
[0] => NA1
[1] => 5
[2] =>
)
Array
(
[0] => IA1
[1] => [1,2,3,4,5]
[2] =>
)
Array
(
[0] => S1
[1] => asadada
[2] =>
)
Array
(
[0] => SA1
[1] => [1,2,3,4,5]
[2] =>
)
But I am expecting 'I8','I1','I2','I3','I4' also in seperated array with position [0]. Any help on how to do this.
You could try something like.
<?php
$str = 'I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];';
preg_match_all('/(?:^|[;:])(\w+)/', $str, $result);
print_r($result[1]); // Matches are here in $result[1]
You can perform a greedy match to match the items between ; and : using preg_match_all()
<?php
$str = 'I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];';
preg_match_all('/;(.+?)\:/',$str,$matches);
print_r($matches[1]);
Live Demo: https://3v4l.org/eBsod
One possible approach is using a combination of explode() and implode(). The result is returned as a string, but you can easily put it into an array for example.
<?php
$input = "I1:1;I2:2;I8:2;NA1:5;IA1:[1,2,3,4,5];S1:asadada;SA1:[1,2,3,4,5];SA1:[1,2,3,4,5];.";
$output = array();
$array = explode(";", $input);
foreach($array as $item) {
$output[] = explode(":", $item)[0];
}
echo implode(",", $output);
?>
Output:
I1,I2,I8,NA1,IA1,S1,SA1,SA1,.

Summary, reorganizing and "flatten" the entire multi-dimensional array

Currently I have an array like :
Array(
[0] => Array([range]=>1-10 [count]=>3 [type]=>A)
[1] => Array([range]=>11-20 [count]=>6 [type]=>A)
[2] => Array([range]=>21-30 [count]=>5 [type]=>A)
[3] => Array([range]=>1-10 [count]=>5 [type]=>B)
[4] => Array([range]=>11-20 [count]=>3 [type]=>B)
[5] => Array([range]=>21-30 [count]=>8 [type]=>B)
[6] => Array([range]=>1-10 [count]=>4 [type]=>C)
[7] => Array([range]=>11-20 [count]=>3 [type]=>C)
[8] => Array([range]=>21-30 [count]=>6 [type]=>C)
[9] => Array([range]=>1-10 [count]=>3 [type]=>D)
[10] => Array([range]=>11-20 [count]=>7 [type]=>D)
And then I am trying to regroup/remake the array depends on their type and the expected output would be like :
Array(
[0] => Array([type]=>A [1-10]=>3 [11-20]=>6 [21-30]=>5)
[1] => Array([type]=>B [1-10]=>5 [11-20]=>3 [21-30]=>8)
[2] => Array([type]=>C [1-10]=>4 [11-20]=>3 [21-30]=>6)
[3] => Array([type]=>D [1-10]=>3 [11-20]=>7)
)
I have tried array_column but isn't what exactly I want...
Example Here.
Thanks in advance.
This should work for you:
Here I simply loop through the entire array and then check with isset() if the result array already has an innerArray with the same type (e.g $result["A"]), if not I add the type as value to the inner array (.e.g. $result["A"]["type"] = "A";).
After this check I simply add the range and count to each type (e.g. $result["A"]["1-10"] = 3;)
At the end I simply reindex the entire $result array with array_values().
<?php
foreach($arr as $k => $v) {
if(!isset($result[$v["type"]]))
$result[$v["type"]]["type"] = $v["type"];
$result[$v["type"]][$v["range"]] = $v["count"];
}
$result = array_values($result);
print_r($result);
?>
output:
Array
(
[0] => Array
(
[type] => A
[1-10] => 3
[11-20] => 6
[21-30] => 5
)
//...
)

Explode array three times

I have a string and I would like to explode with three differents patterns. The string looks like to :
country:00/00/00->link:00/00/00->link2
country2:00/00/00->link3:00/00/00->link4
I would like to get the differents parts of this two strings. The two lines are separated by a /n, the dates are separated by : and the link associated to date are separated with a ->
At the beginning I explode by the line break
$var = explode("\n", $var);
but when I tried to explode again this string, I get an error : *preg_split() expects parameter 2 to be string, array given*
How can I get the different parts ?
Thanks in advance.
Ideone link
Instead of using preg_split, consider using preg_match. You can write it as one big regex.
<?php
// Implicit newline. Adding \n would make an empty spot in the array
$str = "country:00/00/00->link:00/00/00->link2
country2:00/00/00->link3:00/00/00->link4";
$arr = split("\n", $str);
for ($i = 0; $i < count($arr); $i++) {
preg_match("/^(\w+)\:(\d\d\/\d\d\/\d\d)->(\w+)\:(\d\d\/\d\d\/\d\d)->(\w+)/", $arr[$i], $matches);
print_r($matches);
}
?>
Output:
Array
(
[0] => country:00/00/00->link:00/00/00->link2
[1] => country
[2] => 00/00/00
[3] => link
[4] => 00/00/00
[5] => link2
)
Array
(
[0] => country2:00/00/00->link3:00/00/00->link4
[1] => country2
[2] => 00/00/00
[3] => link3
[4] => 00/00/00
[5] => link4
)
EDIT
In your comment, you're posting dates with 4 digits, whereas in your question, they only had 2 digits.
Therefore you need to change the regex to:
/^(\w+)\:(\d\d\/\d\d\/\d\d\d\d)->(\w+)\:(\d\d\/\d\d\/\d\d\d\d)->(\w+)/
How about using preg_match_all:
<?php
$data =<<<ENDDATA
country:00/00/00->link:00/00/00->link2
country2:00/00/00->link3:00/00/00->link4
ENDDATA;
preg_match_all('#(\d{2}/\d{2}/\d{2})->(.[^:\n]+)#', $data, $matches);
print_r($matches);
Gives the following result:
Array
(
[0] => Array
(
[0] => 00/00/00->link
[1] => 00/00/00->link2
[2] => 00/00/00->link3
[3] => 00/00/00->link4
)
[1] => Array
(
[0] => 00/00/00
[1] => 00/00/00
[2] => 00/00/00
[3] => 00/00/00
)
[2] => Array
(
[0] => link
[1] => link2
[2] => link3
[3] => link4
)
)
your problem is that after using explode first time, it is turning into an array and explode function connat explode an array. You need to use a loop probablr for loop that targets array elemets then use explode function on those elements and you will have it.
See example Below:
<?php
$val="abc~~~def~~~ghi####jkl~~~mno~~~pqr###stu~~~vwx~~~yz1";
$val=explode("####", $val);
//result will be
$valWillBe=array(3) {
[0]=>'abc~~~def~~~ghi',
[1]=>'jkl~~~mno~~~pqr',
[2]=>'stu~~~vwx~~~yz1'
}
//if you want to explode again you use a loop
for($r=0; $r<sizeof($val); $r++){
$val[$r]=explode("~~~", $val[$r]);
}
//now you have your string exploded all in places.
?>

preg_match or operator

My code below produces an error, unknown modified "|"... I'm trying to use it as the OR operator. What is the correct way to run this code without error?
$p = "(\w+)|(\()|(\))|(\,)";
$s = "sum(blue,paper,green(yellow,4,toast)))";
preg_match($p,$s, $matches);
print_r($matches);
Edit
Okay I changed it a bit... ~(\w+|\(|\)|,)~
Now... here's the problem: I need to take that string and split it into an array like this:
array("sum","(","blue","paper","green","(" ... etc );
Can someone help me do that? when I run the above expression it outputs an empty array....
Thanks
You are missing the delimiter for your pattern.
$p = "~(\w+)|(\()|(\))|(\,)~";
You're missing the delimiter as #Crayon correctly mentioned, also this pattern does the same thing:
$p = '~(\w+|[(]|[)]|,)~';
As for your (new) problem, try this:
$p = '~([(),])~';
$str = 'sum(blue,paper,green(yellow,4,toast)))';
$res = preg_split($p, $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($res);
Output:
Array
(
[0] => sum
[1] => (
[2] => blue
[3] => ,
[4] => paper
[5] => ,
[6] => green
[7] => (
[8] => yellow
[9] => ,
[10] => 4
[11] => ,
[12] => toast
[13] => )
[14] => )
[15] => )
)

help using php explode () and organizing output

Can someone pls show me how to map this correctly? I am trying to understand how to use php explode() and organizing the values in a way that I can retrieve and print them in some organized matter. For each record I want to put a name=value in a particular bucket. I have (7) max buckets per record. Sometimes I have records that won't fill each bucket.
(for example record (2) is missing attributes (5,6,7) and record (3) is missing attribute (4)).
1-Column=host1.colo.sub;2-Column=Fri Aug 13;3-Column=db9.nfl.colo2.;4-Column=00:00:03;5-Column=01:55:02;6-Column=87.24 MB;7-Column=Success;
1-Column=host1.colo.sub;2-Column=Fri Aug 13;3-Column=pdb2.colo2.;4-Column=04:00:02;
1-Column=host1.colo.sub;2-Column=Fri Aug 13;3-Column=gl3_lvm;5-Column=04:48:06;6-Column=54.64 MB;7-Column=Success;
So far I wrote this to view my output:
<?php
$InputFile = file("test.txt");
foreach ($InputFile as $line){
$pieces = explode(";", $line);
//print $pieces[0];
//print $pieces[1];
//print $pieces[2];
print $pieces[3];
//print $pieces[4];
//print $pieces[5];
//print $pieces[6];
//print_r($line);
}
?>
I would like to print out similar values for each attribute instead of this where its mixed.
Using 'print $pieces[3];'
4-Column=00:00:034-Column=04:00:025-Column=04:48:06
$InputFile = file("test.txt");
foreach ($InputFile as $line){
preg_match('~(1-Column[^;]*;?)?(2-Column[^;]*)?;?(3-Column[^;]*)?;?(4-Column[^;]*)?;?(5-Column[^;]*)?;?(6-Column[^;]*)?;?(7-Column[^;]*)?;?~',$line,$pieces);
$pieces = array_pad($pieces,8,'');
echo "<pre>";print_r($pieces);echo "</pre>";
}
output:
Array
(
[0] => 1-Column=host1.colo.sub;2-Column=Fri Aug 13;3-Column=db9.nfl.colo2.;4-Column=00:00:03;5-Column=01:55:02;6-Column=87.24 MB;7-Column=Success;
[1] => 1-Column=host1.colo.sub;
[2] => 2-Column=Fri Aug 13
[3] => 3-Column=db9.nfl.colo2.
[4] => 4-Column=00:00:03
[5] => 5-Column=01:55:02
[6] => 6-Column=87.24 MB
[7] => 7-Column=Success
)
Array
(
[0] => 1-Column=host1.colo.sub;2-Column=Fri Aug 13;3-Column=pdb2.colo2.;4-Column=04:00:02;
[1] => 1-Column=host1.colo.sub;
[2] => 2-Column=Fri Aug 13
[3] => 3-Column=pdb2.colo2.
[4] => 4-Column=04:00:02
[5] =>
[6] =>
[7] =>
)
Array
(
[0] => 1-Column=host1.colo.sub;2-Column=Fri Aug 13;3-Column=gl3_lvm;5-Column=04:48:06;6-Column=54.64 MB;7-Column=Success;
[1] => 1-Column=host1.colo.sub;
[2] => 2-Column=Fri Aug 13
[3] => 3-Column=gl3_lvm
[4] =>
[5] => 5-Column=04:48:06
[6] => 6-Column=54.64 MB
[7] => 7-Column=Success
)
If your input data is so irregular you would either need to parse it with a bit more code, not just a simple explode, or prepare it so that it works as expected with explode.
In the second case, you could use strpos to find all ";" characters in the string and check if the number after them is in order. If one (or more) number was skipped you should compensate by inserting another ";". This way explode will create an empty array element and all your resulting arrays should be aligned.
While it's not exactly clear what you're trying to accomplish, hopefully this code might help you figure out what's going on.
Note that here, I've added another loop inside the main foreach, to iterate over each name/value pair in the line:
<?php
$InputFile = file("test.txt");
$lineCnt = 0;
foreach ($InputFile as $line){
$lineCnt++;
echo "Processing line #" . $lineCnt. "\n";
$pieces = explode(";", $line);
foreach($pieces as $pair){
$pair = explode('=',$pair);
if (!empty($pair[1])){
print "\t".$pair[0] .' = ' . $pair[1] . "\n";
}
}
}
The script will produce nice-looking output if run from the command-line. If you're running it in the browser, you might want to change the \n's to , and the \t's to or something.
See if this helps...
$splits = explode(';',$_POST['data']);
foreach($splits as $id => $item) {
preg_match('/(.*?)=(.*)/',$item, $matches);
$parts[$matches[1]][] = $matches[2];
}
print_r($parts);
This will give you an array with keys as 1-Column, 2-Column as so on which will contain an array of related value. You can print this array in whatever way you want.
Here is the output:
[1-Column] => Array
(
[0] => host1.colo.sub
[1] => host1.colo.sub
[2] => host1.colo.sub
)
[2-Column] => Array
(
[0] => Fri Aug 13
[1] => Fri Aug 13
[2] => Fri Aug 13
)
[3-Column] => Array
(
[0] => db9.nfl.colo2.
[1] => pdb2.colo2.
[2] => gl3_lvm
)
[4-Column] => Array
(
[0] => 00:00:03
[1] => 04:00:02
)
[5-Column] => Array
(
[0] => 01:55:02
[1] => 04:48:06
)
[6-Column] => Array
(
[0] => 87.24 MB
[1] => 54.64 MB
)
[7-Column] => Array
(
[0] => Success
[1] => Success
)

Categories