This question already has answers here:
How can I explode a string by more than one space, but not by exactly one space in php
(2 answers)
Closed 8 months ago.
I am reading from files and each line has multiple spaces. Example:
$line = 'Testing Area 1 10x10';
I need to convert it into array with 3 elements only so I can save it to a table. Final output should be like this:
$final_array = array('Testing Area', '1', '10x10');
This is how I'm doing it so far:
// read by line
foreach(explode(PHP_EOL, $contents) as $line) {
// split line by 2 spaces coz distance between `1` and `10x10` is atleast 2 spaces
$arr = explode(' ', $line);
// But because `Testing Area` and `1` has so many spaces between them,
// exploding the $line results to empty elements.
// So I need to create another array for the final output.
$final_array = array();
// loop through $arr to check if value is empty
// if not empty, push to $final array
foreach ($arr as $value) {
if (!empty($value)) {
array_push($final_array, $value);
}
}
// insert into table the elements of $final_array according to its column
}
Is there a better way to do this instead of looping through the array and checking each element if it's empty?
Take note that I have multiple files to read, each containing atleast 200 lines like that.
Use preg_split(), with 2 or more spaces as the delimiter.
$array = preg_split('/\s{2,}/', $line);
Assuming the criteria for splitting be two or more spaces, we can try using preg_split here:
$line = 'Testing Area 1 10x10';
$final_array = preg_split("/\s{2,}/", $line);
print_r($final_array);
This prints:
Array
(
[0] => Testing Area
[1] => 1
[2] => 10x10
)
Related
I am a newbie here and I have a php array of some strings, such as {"VAL1","VAL2", "VAL3", "VAL4"} and I have a larger string (normally a text file). The text file contains the elements of the arrays at different positions and some or all may be repeating more than one. Each of of the elements of the array that are contained in the text file are immediately followed by a time of occurence, for example, "VAL1 0900UTC and other text information".The problem now is that I want to find the occurrence(s) of all of the elements of the array in the text file and the time value following the element.
Please note that some of the elements may occur more than once at different positions with different time value in the textfile.
Already, I can load the textfile and get all of the elements.:
$mytextfile = preg_replace('/\s+/', ' ', strtoupper(file_get_contents($textpath."/". $textfile)));
$substr = array("REALTK","BGPTK", "SUDTK", "BECTK");
$bigstring = "REALTK 1000UTC 16/14 1011 BGPTK 1030UTC 10/12 992 REALTK 1145UTC 00/14 2222 SUDTK 1412UTC 11/06 1011 REALTK 1600UTC 16/14 1015 ...";
//I created variables to hold all element occuring to false
$is_val1 = false; $is_val2 = false;$is_val3 = false; $is_val4 = false;
//I created variables to count how many of each substring exist in the string
$numofval1=$numofval2=$numofval3=$numofval4=0;
if(strpos($bigstring, $substr[0]) !== false) {
$is_val1 = true;
//if exist, count how many times
$numofval1 = substr_count(strtoupper($bigstring),$substr[0]);
} e.t.c
I have been able to get the occurrence of each of the array elements in the big string
I have been able to detect if any of the array elements occur more than once in big string and number of times it does.
But I have not being able to get them in the sequence they occur with their position in the textfile string and the time value after each element.
$mytextfile = preg_replace('/\s+/', ' ', strtoupper(file_get_contents($textpath."/". $textfile)));
$substr = array("REALTK","BGPTK", "SUDTK", "BECTK");
//this is a sample content of the textfile
$bigstring = "REALTK 1000UTC 16/14 1011 BGPTK 1030UTC 10/12 992 REALTK 1145UTC 00/14 2222 SUDTK 1412UTC 11/06 1011 REALTK 1600UTC 16/14 1015 ...";
//I created variables to hold all element occuring to false
$is_realtk = false; $is_bgptk = false;$is_sudtk = false; $is_bectk = false;
//I created variables to count how many of each of the element exist in the text file string
$numofrealtk=$numofbgptk=$numofsudtk=$numofbectk=0;
if(strpos($bigstring, $substr[0]) !== false) {
$is_realtk = true;
//if exist, count how many times
$numofrealtk = substr_count(strtoupper($bigstring),$substr[0]);
} e.t.c
What I need is to get the Elements of the array in the order in which they occur in the text file with their position and time value
REALTK POSITION1 1000UTC
BGPTK POSITION5 1030UTC
REALTK POSITION8 1145UTC
SUDTK POSITION13 1412UTC
REALTK POSITION17 1600UTC
I also want to store the element => timevalue as associative array.
Thanks in anticipation.
Here is the snippet for you, please see inline doc for explanation
$substr = array("VAL1","VAL2", "VAL3", "VAL4");
$bigstring = "OTHERS VAL1 VAL4 VAL1 OTHERS OTHERS VAL2 OTHERS";
// considering space to explode words and having numbers in it
$temp = array_unique(str_word_count($bigstring, 1,"0..9"));
// sorting generated array and keeping index of value
asort($temp);
// matching records from array
$temp = array_intersect($temp,$substr);
// showing all the data you want
array_walk($temp,function($item,$k){
echo $item.' POSITION '.$k."\n"; // replace \n with <br/> if web
});
Working demo.
If the elements in your $bigstring are always divided by a whitespace, you can explode:
$val_arr = array( "REALTK" => array(), "BGPTK" => array(), "SUDTK" => array(), "BECTK" => array();
$bigstring_arr = explode( " ", $bigstring);
foreach( $bigstring_arr as $key => $part ){
if( in_array( $part, $substr ) ){
$val_arr[$part][] = array( "position" => $key+1, "time" => $bigstring_arr[$key+1] );
}
}
If it's not you can also explode directly on each element of Val1, Val2... . The code gets a bit more complicated then. But it would work as well if you created a new array in the form of "CountOfAllCharsInBigstringBeforeOccurence" => "KeyOfValInSubstr". From that you can derive your ordering with the vals.
Edit:
I edited the code based on your comment. Please note that it is not possible to have an array that has the same key multiple times which is why the solution here will have multiple dimensions.
Example
I have CSV file that contains data of random number example data in CSV :
639123456789,73999999999,739222222222,839444444444,8639555555555....more
So, if I upload it, I want it to explode in a variable or in an array as long as I get the specific data. example of data I want to get is all 2 first line starting at 73 be extract so meaning all numbers that start with 73 only.
Example: 73999999999,739222222222
I have tried it by using only 1 number using split,substr and explode function but my problem is if the user input a CSV bulk data with no limit.
You can use substr() and loop through your array deleting the elements that do not match.
$str = '639123456789,73999999999,739222222222,839444444444,8639555555555';
$array = explode(',', $str); //Convert your string to an array.
$searchString = '73'; //Set the value your looking for.
foreach($array as $key=>$value){
if(substr($value, 0, 2) != $searchString){ //This will test first two characters.
unset($array[$key]);
}
}
$array = array_values($array);
print_r($array);
This will output:
Array
(
[0] => 73999999999
[1] => 739222222222
)
Updated
This will make a new array with only the numbers you want in it, leaving the original array untouched.
$str = '639123456789,73999999999,739222222222,839444444444,739222222222,839444444444,839444444444,73999999999';
$array = explode(',', $str);
$searchString = '73';
foreach($array as $key=>$value){
if(substr($value, 0, 2) == $searchString){
$results[] = $value;
}
}
print_r($results);
This question already has answers here:
Remove empty array elements
(27 answers)
Closed 6 years ago.
I have a textarea box that takes barcodes separated by a new line. When they are processed, the new lines become commas. But if somebody inputs:
123456
234567
...
with a bunch of spaces under each code as such, it then becomes
$barcode_list = 123456,,,234567
I am able to strip the commas from the end, and I have tried:
$array = explode(",", $barcode_list);
foreach($array as $item){ //Separate each item
if ($item == "") {
unset($item);
}
but it doens't seem to work, I still get mysqli errors etc. Is there any way to get around this?
You should first remove unnecessary commas, then explode. Fewer steps...
// every sequence of commas becomes one comma
$barcode_list=preg_replace("/,+/",",",$barcode_list);
// explode the string into an array
$array = explode(",", $barcode_list);
You're doing an unset that doesn't really affect your array.
Do this:
$array = explode(",", $barcode_list);
foreach($array as $key => $item){ //Separate each item
if ($item == "") {
unset($array[$key]);
}
}
I have an array like:
array{
0 => string 'B.E - ECE',
1 => string 'B.E - EEE',
2 => string 'Msc - Maths',
3 => string 'Msc - Social',
}
So how can I make the array into groups like:
B.E. => ECE, EEE
Msc => Maths,Social
?
I want to do it in PHP. Can anybody help me how to achieve it ?
So is your array split by the "-" character?
so it's Key - Value pairs split by commas?
Ok -
(edit: section removed to clarify answer)
Following conversation and some rearrangement of the question, a second try at a solution, with the above assumptions, try this:
$array = array {
0 => string 'B.E - ECE' (length=9)
1 => string 'B.E - EEE' (length=9)
2 => string 'Msc - Maths' (length=11)
3 => string 'Msc - Social' (length=12)
}
foreach ($array as $row){
$piece = explode("-",$row);
$key = $piece[0];
$newArray[$key][] = $piece[1];
unset($piece);
}
unset($row) ///tidy up
This will output two arrays each of two arrays:
$newArray[Msc] = array("Maths","Social");
$newArray[B.E] = array("ECE","EEE");
What I did was cause the Foreach loop to automatically add onto the array if the key exists with $newArray[$key][] so that the values are automatically collected by key, and the key is defined as the first half of the original array values.
Printing:
To print the result:
foreach($newArray as $key=>$newRow){
/// there are two rows in this case, [B.E] and [MSc]
print $key.":<br>";
print "<pre>";
///<pre> HTML tag makes output use linebreaks and spaces. neater.
print_r($newRow);
///alternatively use var_dump($newRow);
print "</pre>";
}
Alternatively if you wish to print a known named variable you can write:
print_r($newArray['B.E']);
Which will print all the data in that array. print_r is very useful.
what you want is php's explode. Not sure if this will give you the perfect answer but should give you an idea of what to do next.
$groupedArray = array();
foreach($array as $row){
$split = explode(" - ",$row);
$groupedArray[] = $split[0];
}
array_unique($groupedArray); //This will give you the two groupings
foreach($array as $row){
$split = explode(" - ",$row);
$pos = array_search($split[0],$groupedArray);
if($pos !== FALSE){
$groupedArray[$pos][] = $split[1];
}
}
This should give you a full formatted array called $groupedArray where $array is the array you already have.
Hope this helps!
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How do i Loop through the hidden field items and put in Session using PHP
I have a hidden Field which contains this format which contains the Set of rows separated by ';'(semicolon)
and each row contains some columns name separated by ':' (colon) and each column value separated by ',' (comma)
so my format would be ENO:123,ENAME:XYZ,SAL:1200; ENO:598,ENAME:AIR,SAL:1300; which is what stored in hidden field
So How do i grab each column such as ENO ,ENAME and SAL their values for any number of rows written to hidden field
so i have my own custom session function where i can set the key and value .So on looping the values
I should be able to put MyCustomSessionFunction('ENAME',??????).How do i fill this .
I did not get Proper Replies Earlier .can anyone please help me
$hiddenformat = $_POST['hiddenfield'];
string(80) "ENO:1000,ENAME:B,SAL:10;ENO:1000,ENAME:S,SAL:100;"
when i vardump($hiddenformat) I am getting the above format .How do i explode and loop and assign each value to my
custom session function
foreach( $outer_array as $outer_key => $inner_array )
{
foreach( $inner_array as $key => $value )
{
}
}
$hiddenformat = $_POST['hiddenfield'];
$parts = explode(',', $hiddenformat);
foreach($parts as $part) {
$bits = explode(':', $part);
...
}
Given a $hiddenformat of ENO:1000,ENAME:B,SAL:..., the first explode will split the line at every comma, giving you a $parts array that looks like:
$parts = array(
0 => 'ENO:1000',
1 => 'ENAME:B',
2 => 'SAL:.....
);
Yuu use foreach to loop over this $parts array, and split the $part at every colon (:). So at each stage, $bits will look like:
$bits = array(
0 => 'ENO',
1 => '1000'
)
and then on the next iteration will
$bits = array(
0 => 'ENAME',
1 => 'B'
)
and so on. What you do with those individual chunks is up to you.
And yes, this was all present in the answers of the other questions. You just had to do a bit of work to put it all together.
Yeah, it was.
It's just to say that around that, you have to explode() by ";" and in the loop use Marc's code, since there are multiple Sets of data in the string