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.
Related
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
)
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);
I am a noob attempting to solve a program for a word search app I am doing. My goal is to take a string and compare how many times each letter of that string appears in another string. Then put that information into an array of key value pairs, where the key is each letter of the first string and the value is the number of times. Then order it with ar(sort) and finally echo out the value of the letter that appears the most (so the key with the highest value).
So it would be something like array('t' => 4, 'k' => '9', 'n' => 55), echo the value of 'n'. Thank you.
This is what I have so far that is incomplete.
<?php
$i = array();
$testString= "endlessstringofletters";
$testStringArray = str_split($testString);
$longerTestString= "alphabetalphabbebeetalp
habetalphabetbealphhabeabetalphabetalphabetalphbebe
abetalphabetalphabetbetabetalphabebetalphabetalphab
etalphtalptalphabetalphabetalbephabetalphabetbetetalphabet";
foreach ($testStringArray AS $test) {
$value = substr_count($longerTestString, $testStringArray );
/* Instead of the results of this echo, I want each $value to be matched with each member of the $testStringArray and stored in an array. */
echo $test. $value;
}
/* I tried something like this outside of the foreach and it didn't work as intended */
$i = array_combine($testStringArray , $value);
print_r($i);
If I understand correctly what you are after, then it's as simple as this:
<?php
$shorterString= "abc";
$longerString= "abccbaabaaacccb";
// Split the short sring into an array of its charachters
$stringCharachters = str_split($shorterString);
// Array to hold the results
$resultsArray = array();
// Loop through every charachter and get their number of occurences
foreach ($stringCharachters as $charachter) {
$resultsArray[$charachter] = substr_count($longerString,$charachter);
}
print_r($resultsArray);
I have a challenge that I have not been able to figure out, but it seems like it could be fun and relatively easy for someone who thinks in algorithms...
If my search term has a "?" character in it, it means that it should not care if the preceding character is there (as in regex). But I want my program to print out all the possible results.
A few examples: "tab?le" should print out "table" and "tale". The number of results is always 2 to the power of the number of question marks. As another example: "carn?ati?on" should print out:
caraton
caration
carnaton
carnation
I'm looking for a function that will take in the word with the question marks and output an array with all the results...
Following your example of "carn?ati?on":
You can split the word/string into an array on "?" then the last character of each string in the array will be the optional character:
[0] => carn
[1] => ati
[2] => on
You can then create the two separate possibilities (ie. with and without that last character) for each element in the first array and map these permutations to another array. Note the last element should be ignored for the above transformation since it doesn't apply. I would make it of the form:
[0] => [carn, car]
[1] => [ati, at]
[2] => [on]
Then I would iterate over each element in the sub arrays to compute all the different combinations.
If you get stuck in applying this process just post a comment.
I think a loop like this should work:
$to_process = array("carn?ati?on");
$results = array();
while($item = array_shift($to_process)) {
$pos = strpos($item,"?");
if( $pos === false) {
$results[] = $item;
}
elseif( $pos === 0) {
throw new Exception("A term (".$item.") cannot begin with ?");
}
else {
$to_process[] = substr($item,0,$pos).substr($item,$pos+1);
$to_process[] = substr($item,0,$pos-1).substr($item,$pos+1);
}
}
var_dump($results);
I have some data in the format of
C222 = 50
C1234P687 = 'some text'
C123YYY = 'text'
C444 = 89
C345 = 3
C122P687 = 'some text'
C122YYY = 'text'
....
....
so basically 3 different forms
"C" number = value, example - C444 = 89
"C" number "P" number = value, example - C123P687 = 'some text'
"C" number "YYY" = value
Only number is of variable length on the left side of (=) sign. Values vary.
I want to store the data in db as
INSERT INTO datatable
c_id = "number after C"
p_id = "number after P" // if it exists for a line of data
value = 'value'
yyy = 'value'
Any ideas how to retrieve these numbers?
Thanks
Use regular expressions in PHP. The following regular expression pattern will match all cases you've provided - use it with preg_match_all (pass in an array and PREG_SET_ORDER) and the array you passed in will then contain an array per row of your data, and each row's array will contain 5 elements.
(C[\d]+)(P[\d]+)?(YYY)? = (.+)
The first element of the array will contain the complete string that was tested.
The second element of the array will contain the "C" number.
The third element of the array will contain the "P" number if present, otherwise it'll be blank.
The fourth element of the array will contain "YYY" if present, otherwise it'll be blank.
The fifth element of the array will contain the value.
In response to an earlier comment, the following regex is a modified version of the above, but will not include the C and P in the matched values:
C([\d]+)(?:P([\d]+))?(YYY)? = (.+)
I am assuming the data is read in from a file, so using something like file_get_contents or fopen.
For the data regular Expressions is you best bet..
Take a look at http://php.net/manual/en/function.preg-match-all.php
# UPDATE REG EX UPDATED
preg_match_all("|C([\d]+)(?:P([\d]+))?(YYY)? = (.+)|", $yourDataLine, $out, PREG_SET_ORDER);
$out[0] = TESTED STRING e.g. C123 = 456;
$out[1] = C;
$out[2] = P;
$out[3] = YYY;
$out[4] = VALUE;
reg expression thanks to: Andy Shellam
A solution without using regular expressions:
<?php
$s="C23YYY = 'hello world'";
$p1=explode('=',$s);
$left=trim($p1[0]);
$right=trim($p1[1]);
$value=$right;
if(substr($left,-3)!='YYY'){
$pos=strpos($left,'P');
if($pos!==false){
$c_id=substr($left,1,$pos-1);
$p_id=substr($left,1+$pos-strlen($left));
}else{
$c_id=substr($left,1-strlen($left));
}
}else{
$c_id=substr($left,1,strlen($left)-4);
$yyy='YYY';
}
print("c_id = $c_id <br/>");
print("p_id = $p_id <br/>");
print("value = $value <br/>");
print("yyy = $yyy <br/>");
?>