Below script is shown search string in a text file, my text file has contents like:
60, 1, 1, 188, pdgje5566
60, 1, 1, 188, pdgje5565
if(!empty($extTxId)){
$searchfor = $extTxId;
$matches = array();
$handle = #fopen($file, "r");
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(strpos($buffer, $searchfor) !== FALSE)
$matches[] = $buffer;
}
fclose($handle);
}
print_r($matches);
it output as
Array ( [0] => 60, 1, 1, 188, ppje5566 )
however i want to explode the data which is separate by comma(,) and store into variable, is that anyway to do it?
thanks.
i want to explode the data which is separate by comma(,)
Use explode().
If this is a CSV file (or some other delimited file), I suggest looking at fgetcsv(). It is effectively fgets() and explode(), which seems to be what you need.
Since you have spaces between each comma, you can trim each element.
// Iterate through each item int the array (you can do $matches[0] if you just want the first)
foreach ($matches as $match)
{
$output_array = array_map('trim',explode(',',$match));
print_r($output_array);
}
Output:
Array
(
[0] => 60
[1] => 1
[2] => 1
[3] => 188
[4] => pdgje5565
)
Example: http://codepad.org/aSyVX5Bj
Try like
foreach(Array[0] as $element)
{
echo $element;
}
If you know the exact structure of the input you're getting, you could do something like:
$string = '60, 1, 1, 188, pdgje5565';
// Using trim just to be sure
list($varA, $varB, $varC, $varD, $varE) = explode(', ', trim($string));
This way you would get the results as follows:
$varA = 60;
$varB = 1;
$varC = 1;
$varD = 188;
$varE = 'pdgje5565';
The main advantage here is you would get decent variables instead of array with abstract indexes, but it is only good if you're sure about you're structure being constant.
Related
I want to create dynamic associative array from two array's
one array is be used ($l_arr) for key and other array is used for value ($r_arr) when i display $map in output i can see there is associative array created but when i print echo $map['key'] output is blank please help me guyz. here is the code and output,
<?php
$handle = fopen ("php://stdin","r");
fscanf($handle,"%d",$n);
for($i=0;$i<$n;$i++)
{
$arr_temp = fgets($handle);
$l_arr[$i]= preg_replace("/[0-9,.]/", "", $arr_temp);
$r_arr[$i]=preg_replace("/[^0-9,.]/", "", $arr_temp);
}
for($i=0;$i<$n;$i++)
{
$arr_temp = fgets($handle);
$op[$i]=$arr_temp;
}
for($i=0;$i<$n;$i++)
{
$map[$l_arr[$i]]=$r_arr[$i];
}
print_r($map);
echo "value of sam is".$map['sam'];
?>
and output is
Array
(
[sam
] => 99912222
[tom
] => 11122222
[harry
] => 12299933
)
value of sam is
As you can probably see, there are whitespaces in your output - look at new lines after each array index. You need to trim() your preg_replace() here:
$l_arr[$i] = trim(preg_replace("/[0-9,.]/", "", $arr_temp));
$r_arr[$i] = trim(preg_replace("/[^0-9,.]/", "", $arr_temp));
I'm looking to get an array of ID's from the following string.
[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]
Ideally, i'd like to look at this string and get an array of the INT values within images. e.g.
array("3057", "2141", "234");
find images value and explode it to receive array
$str = '[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]';
if (preg_match('/images\s*=\s*\"([^\"]+)\"/', $str, $m)) {
$res = explode(',', $m[1]);
print_r($res);
}
Another solution using explode and strpos functions:
$str = '[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]';
foreach (explode(" ", $str) as $v) {
if (strpos($v, "images=") === 0) {
$result = explode(",", explode('"', $v)[1]);
break; // avoids redundant iterations
}
}
print_r($result);
The output:
Array
(
[0] => 3057
[1] => 2141
[2] => 234
)
I am trying to import a CSV for a shop, with a subset of data from an existing CSV file. I need to split one item from a column (column 3, category_id) that contains multiple comma-separated values, then combine it with one other column (Product_id) to produce multiple rows in the import CSV. See the following examples.
Original CSV
Product_id;article_id;category_id;
"1";"0001";"2,4,6"
Need it into a new CSV file
Product_id;category_id
"1";"2"
"1","4"
"1","6"
I tried just the fegetcsv function to read in the CSV and to printout the whole into an array but I have no idea what to do next.
<?php
$handle = fopen ("articles.csv","r");
while ( ($data = fgetcsv ($handle, 1000, ";")) !== FALSE ) {
$column3[] = $data[3];
}
fclose ($handle);
//edit:
print_r($column3);
?>
I get:
Array ([0] => category_id [1] => 1 [2] => 0001 [3] => 2,4,6
Quick and dirty:
$csvData = file('articles.csv');
$matches = array();
$output = "";
foreach($csvData as $csvLine) {
if(preg_match('/"(.+)";".+";"(.+)"/', $csvLine, $matches))
{
$numbers = explode(',', $matches[2]);
foreach($numbers as $number) {
$output .= "\"{$matches[1]}\";\"{$number}\"" . PHP_EOL;
}
}
}
I have file with a lot of rows (over 32k). Rows looks like:
34 Item
5423 11Item
44 Item
First digits it is IDs. I want make assoc. array: array("34" => "Item", "5423" => "11Item", "44" => "Item")
IDs can be from 1 to 5 length (1 - 65366)
Name of item can start from with a digit
Minimum one (BUT can be MORE than one) space between IDs and Items name
So main divide is space or certain number of them. Using PHP.
You can use this:
$data = <<<'LOD'
34 Item
5423 11Item
44 Item
546
65535 toto le héros
65536 belzebuth
glups glips
LOD;
$result = array();
$line = strtok($data, "\r\n");
while($line!==false) {
$tmp = preg_split('~\s+~', $line, 2, PREG_SPLIT_NO_EMPTY);
if (count($tmp)==2 && $tmp[0]==(string)(int)$tmp[0] && $tmp[0]<65536)
$result[$tmp[0]] = $tmp[1];
$line = strtok("\r\n");
}
print_r($result);
Here's a method which doesn't check validity of data but might works. It explodes every line according to space(s) and put results in a $res associative array.
For information, preg_split() allows to split a string with a regex.
$res = array();
foreach($lines as $line) {
$data = preg_split('/\s+/', $line);
$res[$data[0]] = $data[1];
}
If you really want to check your conditions you can add some if statement, with the ID limit:
$res = array();
foreach($lines as $line) {
$data = preg_split('/\s+/', $line);
$idx = intval($data[0]);
if($idx > 0 && $idx < 65366) // skip lines where the ID seems invalid
$res[$data[0]] = $data[1];
}
Use preg_match with named capturing groups:
preg_match('/^(?<id>\d+)\s+(?<name>[\w ]+)$/', $row, $matches);
$matches['id'] will contain the ID and $matches['name'] will contain the name.
while (/* get each row */) {
preg_match('/^(?<id>\d+)\s+(?<name>[\w ]+)$/', $row, $matches);
$id = $matches['id'];
$name = $matches['name'];
if ($id > 1 && $id < 65366) {
$arr[$id] = $name;
}
}
print_r($arr);
Example output:
Array
(
[34] => Item
[5423] => 11Item
[44] => Item
[3470] => BLABLA TEF2200
)
Demo
Use http://uk3.php.net/preg_split
i.e.
preg_split("/ +/", $line);
It will return an array of strings.
Looking for php help, best practice. What is a good way to break these lines? I was looking into explode or is a regex better? and then maybe display them into a table? thanks for your input.
input file:
PRE:abc:KEY1:null:KEY2:/myproject/data/dat_abc_2010120810.gz1
PRE:def:KEY1:sdsu:KEY2:mail_abc.dat.2010120810.gz1
expected output or web page for display:
PRE KEY1 KEY2
=== ==== ======================================
abc null /myproject/data/dat_abc_2010120810.gz1
def sdsu mail_abc.dat.2010120810.gz1
If you have a file like that I would do it in two steps if I were you...
1st step
Use file() to get an array representing the file.
2nd step
Now you can use explode() to get all the different columns and output them.
Quick example:
<?php
$output = "";
$file = file("data.txt");
foreach ($file as $line)
{
$cols = explode (":", $line);
$output .= "{$cols[0]} {$cols[1]}";
}
?>
Hope this helps.
explode will work just fine:
$fp = fopen('myfile.txt', 'r');
while ($line = fgets($fp))
$parts = explode(':', $line);
$array = array();
for ($i=0; $i<count($parts); $i+=2) {
$array[$parts[$i]] = isset($parts[$i+1]) ? $parts[$i+1] : 'null';
}
print_r($array);
}
Will output:
Array
(
[PRE] => abc
[KEY1] => null
[KEY2] => /myproject/data/dat_abc_2010120810.gz1
)
Array
(
[PRE] => def
[KEY1] => sdsu
[KEY2] => mail_abc.dat.2010120810.gz1
)