Get two words (numbers) around a certain text in a string - php

There's a certain contents (from a webpage) where I need to get two numbers of a certain list.
Basically the list goes like:
..... 10 from 12....
..... 1 from 20....
..... 20 from 100...
and so on. For me, I need to get these numbers surrounding the word "from", so I can perform certain calculations with them later.
I looked into this and tried different ways to perform it with strpos or strstr but nothing worked. Does anyone have any idea how to accomplish something like that?

$text = "..... 10 from 12 etc....
..... 1 from 20....
..... 20 from 100...";
$r = preg_match_all('~(\d+) *from *(\d+)~u',$text,$match, PREG_SET_ORDER);
var_export($match);
Output:
array (
0 =>
array (
0 => '10 from 12',
1 => '10',
2 => '12',
),
1 =>
array (
0 => '1 from 20',
1 => '1',
2 => '20',
),
2 =>
array (
0 => '20 from 100',
1 => '20',
2 => '100',
),
)
Explanations:
\d+ one digit or more
(\d+) the sequence in brackets -> the digits in the result array
* no, one or more spaces
from the word from

Here is an example of what you can do with explode:
<?php
/* the text with many different gaps and mess! */
$text = "wlfsdjf;sd sdfljsdfk kfgjdlg d 10 from 200 kflgjdkgdklgsd slfksjd
dfgdf fgdlkjdf d 20 from 30 ldk;lfsd
dflksdjf 40 from 50 dkf;sd sdjfs ";
/* main array */
$array = explode("\n",$text);
echo '<pre>';
print_r($array);
/* looping and clearing out our values per line */
foreach($array as $k => $line){
$f = explode(" ",explode(" from ",$line)[0]);
$f = array_pop($f);
$numbers[$k]['first'] = $f;
$s = explode(" ",explode(" from ",$line)[1]);
$s = $s[0];
$numbers[$k]['second'] = $s;
}
/* our new array set per line */
print_r($numbers);
Will return:
Array
(
[0] => wlfsdjf;sd sdfljsdfk kfgjdlg d 10 from 200 kflgjdkgdklgsd slfksjd
[1] => dfgdf fgdlkjdf d 20 from 30 ldk;lfsd
[2] => dflksdjf 40 from 50 dkf;sd sdjfs
)
Array
(
[0] => Array
(
[first] => 10
[second] => 200
)
[1] => Array
(
[first] => 20
[second] => 30
)
[2] => Array
(
[first] => 40
[second] => 50
)
)

Related

php split / cluster binary into chunks based on next 1 in cycle

I need to figure out a method using PHP to chunk the 1's and 0's into sections.
1001 would look like: array(100,1)
1001110110010011 would look like: array(100,1,1,10,1,100,100,1,1)
It gets different when the sequence starts with 0's... I would like it to segment the first 0's into their own blocks until the first 1 is reached)
00110110 would look like (0,0,1,10,1,10)
How would this be done with PHP?
You can use preg_match_all to split your string, using the following regex:
10*|0
This matches either a 1 followed by some number of 0s, or a 0. Since a regex always tries to match the parts of an alternation in the order they occur, the second part will only match 0s that are not preceded by a 1, that is those at the start of the string. PHP usage:
$beatstr = '1001110110010011';
preg_match_all('/10*|0/', $beatstr, $m);
print_r($m);
$beatstr = '00110110';
preg_match_all('/10*|0/', $beatstr, $m);
print_r($m);
Output:
Array
(
[0] => Array
(
[0] => 100
[1] => 1
[2] => 1
[3] => 10
[4] => 1
[5] => 100
[6] => 100
[7] => 1
[8] => 1
)
)
Array
(
[0] => Array
(
[0] => 0
[1] => 0
[2] => 1
[3] => 10
[4] => 1
[5] => 10
)
)
Demo on 3v4l.org

PHP convert formatted string (title + values) to multidimensional array

I would like to convert this formatted string to multidimensional array but I can't manage to do it.
The goal is to extract titles header (Dreg Time, FN, SS_ID, MAC, Sector ID, Type, Reason, CMPNT, Basic, Cid) and associating the corresponding values.
Because in the finality I would need to process the data in the "Reason" column.
String:
$log = ": mss get dereg_log 2 500
---------- MODEM 2 MAC ---------
Dreg Time FN SS_ID MAC Sector ID Type Reason CMPNT Basic Cid
2017/08/29 08:20:39:627 0x4da9f0 8277 00:24:a0:xx:xx:xx 1 2 25 0 86
2017/08/29 07:17:33:478 0x421c02 8238 00:23:a2:xx:xx:xx 1 3 59 0 47
2017/08/29 06:00:43:232 0x340a41 8508 00:23:a2:xx:xx:xx 1 1 6 13 317
Total Deregistrations since sector active in sector 1: 9576
Derigistrations since dreg log last reset in sector 1: 9576
Deregistration Types:
DEREG_MSS_IMMEDIATE = 0
DEREG_MSS_DREG_REQ_FROM_AP = 1
DEREG_MSS_DREG_REQ_FROM_MS = 2
DEREG_MSS_RNG_RSP_ABORT_FROM_AP = 3
DEREG_MSS_CONTACT_LOST = 4
---------------------------------
2017-Aug-29 08:31:53.860";
Desired Array:
Array
(
[0] => Array
(
[Dreg Time] => '2017/08/29 08:20:39:627'
[FN] => '0x4da9f0'
[SS_ID] => '8277'
[MAC] => '00:24:a0:xx:xx:xx'
[Sector ID] => '1'
[Type] => '2'
[Reason] => '25'
[CMPNT] => '0'
[Basic Cid] => '86'
)
[1] => Array
(
[Dreg Time] => '2017/08/29 07:17:33:478'
[FN] => '0x421c02'
[SS_ID] => '8238'
[MAC] => '00:23:a2:xx:xx:xx'
[Sector ID] => '1'
[Type] => '3'
[Reason] => '59'
[CMPNT] => '0'
[Basic Cid] => '47'
)
[2] => Array
(
[Dreg Time] => '2017/08/29 06:00:43:232'
[FN] => '0x340a41'
[SS_ID] => '8508'
[MAC] => '00:23:a2:xx:xx:xx'
[Sector ID] => '1'
[Type] => '1'
[Reason] => '6'
[CMPNT] => '13'
[Basic Cid] => '317'
)
)
Code tried:
echo '<pre>';
// remove blank lines
$log = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $log);
// remove new lines
$log = preg_replace('/^.+\n.+\n/', '', $log);
$lines = explode( "\n\n", $log );
$return = array();
foreach ($lines as $line) {
$items = explode("\n", $line);
$return[array_shift($items)] = $items;
}
print_r($return);
Result:
Array
(
[Dreg Time FN SS_ID MAC Sector ID Type Reason CMPNT Basic Cid] => Array
(
[0] => 2017/08/29 08:20:39:627 0x4da9f0 8277 00:24:a0:xx:xx:xx 1 2 25 0 86
[1] => 2017/08/29 07:17:33:478 0x421c02 8238 00:23:a2:xx:xx:xx 1 3 59 0 47
[2] => 2017/08/29 06:00:43:232 0x340a41 8508 00:23:a2:xx:xx:xx 1 1 6 13 317
[3] => Total Deregistrations since sector active in sector 1: 9576
[4] => Derigistrations since dreg log last reset in sector 1: 9576
[5] => Deregistration Types:
[6] => DEREG_MSS_IMMEDIATE = 0
[7] => DEREG_MSS_DREG_REQ_FROM_AP = 1
[8] => DEREG_MSS_DREG_REQ_FROM_MS = 2
[9] => DEREG_MSS_RNG_RSP_ABORT_FROM_AP = 3
[10] => DEREG_MSS_CONTACT_LOST = 4
[11] => ---------------------------------
[12] => 2017-Aug-29 08:31:53.860
)
)
Your code was an incomplete attempt, and contained a few errors - e.g. you removed newlines from the log, and then tried split the string based on newlines! Then you tried to split a single line by newline, when clearly a single line cannot, by implication, contain a newline. Also the code just naively ran through each line and added it directly to the array rather than creating an associative array within each index, as shown in the desired output. And lastly it did nothing to try and identify which lines actually contained the desired output.
This will do it:
$log = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $log);
$lines = explode( "\n", $log );
$return = array();
foreach ($lines as $line) {
$line = preg_replace("/\s+/", " ", $line); //condense and standardise the whitespace between each item, so that explode can work.
$items = explode(" ", $line);
if (count($items) == 10 && preg_match("/^[0-9]{4}/", $items[0])) //restrict to lines starting with the year, and with the correct number of columns
$return[] = array(
"Dreg Time" => $items[0]." ".$items[1],
"FN" => $items[2],
"SS_ID" => $items[3],
"MAC" => $items[4],
"Sector_ID" => $items[5],
"Type" => $items[6],
"Reason" => $items[7],
"CMPNT" => $items[8],
"Basic_Cid" => $items[9]
);
}
echo "<pre>".var_export($return, true)."</pre>";

loop through multidimensional array and order sub-array by scores

I am trying to calculate the winning order of golfers when they are tied in a competition.
These golf competitions are using the "stableford" points scoring system, where you score points per hole with the highest points winning. Compared to normal golf "stroke play" where the lowest score wins (though this also has the countback system, only calculating the lowest score in the event of a tie...)
The rules are to use a "countback". i.e., if scores are tied after 9 holes, the best placed of the ties is the best score from the last 8 holes. then 7 holes, etc.
The best I can come up with is 2 arrays.
An array with all the players who tied in a given round. ($ties)
One which has the full score data in (referencing the database playerid) for all 9 holes. ($tie_perhole)
I loop through array 1, pulling data from array 2 and using the following formula to create a temporary array with the highest score:
$max = array_keys($array,max($array));
If $max only has 1 item, this player is the highest scorer. the loop through the first array is "by reference", so on the next iteration of the loop, his playerid is now longer in the array, thus ignored. this continues until there is only 1 playerid left in the first array.
However, it only works if a single player wins in each iteration. The scenario that doesn't work is if a sub-set of players tie on any iterations / countbacks.
I think my problem is the current structure I have will need the original $ties array to become split, and then to continue to iterate through the split arrays in the same way...
As an example...
The $ties array is as follows:
Array
(
[18] => Array
(
[0] => 77
[1] => 79
[2] => 76
[3] => 78
)
)
The $tie_perhole (score data) array is as follows:
Array
(
[18] => Array
(
[77] => Array
(
[9] => 18
[8] => 16
[7] => 14
[6] => 12
[5] => 10
[4] => 8
[3] => 6
[2] => 4
[1] => 2
)
[79] => Array
(
[9] => 18
[8] => 17
[7] => 15
[6] => 14
[5] => 11
[4] => 9
[3] => 7
[2] => 5
[1] => 3
)
[76] => Array
(
[9] => 18
[8] => 16
[7] => 14
[6] => 12
[5] => 10
[4] => 8
[3] => 6
[2] => 4
[1] => 2
)
[78] => Array
(
[9] => 18
[8] => 17
[7] => 15
[6] => 13
[5] => 11
[4] => 9
[3] => 7
[2] => 5
[1] => 3
)
)
)
So in this competition, player's 78 and 79 score highest on the 8th hole countback (17pts), so 1st and 2nd should be between them. Player 79 should then be 1st on the 6th hole countback (14pts, compared to 13pts). The same should occur for 3rd and 4th place with the 2 remaining other players.
There are other scenarios that can occur here, in that within a competition, there will likely be many groups of players (of different amounts) on different tied points through the leaderboard.
Also note, there will be some players on the leaderboard who are NOT tied and stay in their current outright position.
The basics of the working code I have is:
foreach ($ties as $comparekey => &$compareval) {
$tie_loop = 0;
for ($m = 9; $m >= 1; $m--) {
$compare = array();
foreach ($compareval as $tie) {
$compare[$tie] = $tie_perhole[$comparekey][$tie][$m];
}
$row = array_keys($compare,max($compare));
if (count($row) == 1) {
$indexties = array_search($row[0], $ties[$comparekey]);
unset($ties[$comparekey][$indexties]);
// Now update this "winners" finishing position in a sorted array
// This is a multidimensional array too, with custom function...
$indexresults = searchForId($row[0], $comp_results_arr);
$comp_results_arr[$indexresults][position] = $tie_loop;
$tie_loop++;
}
// I think I need conditions here to filter if a subset of players tie
// Other than count($row) == 1
// And possibly splitting out into multiple $ties arrays for each thread...
if (empty($ties[$comparekey])) {
break;
}
}
}
usort($comp_results_arr, 'compare_posn_asc');
foreach($comp_results_arr as $row) {
//echo an HTML table...
}
Thanks in advance for any helpful insights, tips, thoughts, etc...
Robert Cathay asked for more scenarios. So here is another...
The leaderboard actually has more entrants (player 26 had a bad round...), but the code i need help with is only bothered about the ties within the leaderboard.
Summary leaderboard:
Points Player
21 48
21 75
20 73
20 1
13 26
This example produces a $tie_perhole array of:
Array
(
[21] => Array
(
[75] => Array
(
[9] => 21
[8] => 19
[7] => 16
[6] => 14
[5] => 12
[4] => 9
[3] => 7
[2] => 5
[1] => 3
)
[48] => Array
(
[9] => 21
[8] => 19
[7] => 16
[6] => 13
[5] => 11
[4] => 9
[3] => 8
[2] => 5
[1] => 3
)
)
[20] => Array
(
[73] => Array
(
[9] => 20
[8] => 18
[7] => 16
[6] => 13
[5] => 11
[4] => 8
[3] => 6
[2] => 5
[1] => 3
)
[1] => Array
(
[9] => 20
[8] => 17
[7] => 16
[6] => 14
[5] => 12
[4] => 9
[3] => 7
[2] => 4
[1] => 2
)
)
)
In this example, the array shows that players 75 and 48 scored 21 points that player 75 will eventually win on the 6th hole countback (14pts compared to 13pts) and player 48 is 2nd. In the next tied group, players 73 and 1 scored 20 points, and player 73 will win this group on the 8th hole countback and finishes 3rd (18 pts compared to 17 pts), with player 1 in 4th. player 26 is then 5th.
Note, the $tie_loop is added to another array to calculate the 1st to 5th place finishing positions, so that is working.
Hopefully that is enough to help.
Ok, so I don't understand golf at all... hahaha BUT! I think I got the gist of this problem, so heres my solution.
<?php
/**
* Author : Carlos Alaniz
* Email : Carlos.glvn1993#gmail.com
* Porpuse : Stackoverflow example
* Date : Aug/04/2015
**/
$golfers = [
"A" => [1,5,9,1,1,2,3,4,9],
"B" => [2,6,4,2,4,4,1,9,3],
"C" => [3,4,9,8,1,1,5,1,3],
"D" => [1,5,1,1,1,5,4,5,8]
];
//Iterate over scores.
function get_winners(&$golfers, $hole = 9){
$positions = array(); // The score numer is the key!
foreach ($golfers as $golfer=>$score ) { // Get key and value
$score_sub = array_slice($score,0,$hole); // Get the scores subset, first iteration is always all holes
$total_score = (string)array_sum($score_sub); // Get the key
if(!isset($positions[$total_score])){
$positions[$total_score] = array(); // Make array
}
$positions[$total_score][] = $golfer; // Add Golpher to score.
}
ksort($positions, SORT_NUMERIC); // Sort based on key, low -> high
return array(end($positions), key($positions)); // The last shall be first
}
//Recursion is Awsome
function getWinner(&$golfers, $hole = 9){
if ($hole == 0) return;
$winner = get_winners($golfers,$hole); // Get all ties, if any.
if(count($winner[0]) > 1){ // If theirs ties, filter again!
$sub_golfers =
array_intersect_key($golfers,
array_flip($winner[0])); // Only the Worthy Shall Pass.
$winner = getWinner($sub_golfers,$hole - 1); // And again...
}
return $winner; // We got a winner, unless they really tie...
}
echo "<pre>";
print_R(getWinner($golfers));
echo "</pre>";
Ok... Now ill explain my method...
Since we need to know the highest score and it might be ties, it makes no sense to me to maintain all that in separate arrays, instead I just reversed the
golfer => scores
to
Tota_score => golfers
That way when we can sort the array by key and obtain all the golfers with the highest score.
Now total_score is the total sum of a subset of the holes scores array. So... the first time this function runs, it will add all 9 holes, in this case theres 3 golfers that end up with the same score.
Array
(
[0] => Array
(
[0] => A
[1] => B
[2] => C
)
[1] => 35
)
Since the total count of golfers is not 1 and we are still in the 9th hole, we run this again, but this time only against those 3 golfers and the current hole - 1, so we are only adding up to the 8th hole this time.
Array
(
[0] => Array
(
[0] => B
[1] => C
)
[1] => 32
)
We had another tie.... this process will continue until we reach the final hole, or a winner.
Array
(
[0] => Array
(
[0] => C
)
[1] => 31
)
EDIT
<?php
/**
* Author : Carlos Alaniz
* Email : Carlos.glvn1993#gmail.com
* Porpuse : Stackoverflow example
**/
$golfers = [
"77" => [2,4,6,8,10,12,14,16,18],
"79" => [3,5,7,9,11,14,15,17,18],
"76" => [2,4,6,8,10,12,14,16,18],
"78" => [3,5,7,9,11,13,15,17,18]
];
//Iterate over scores.
function get_winners(&$golfers, $hole = 9){
$positions = array(); // The score numer is the key!
foreach ($golfers as $golfer => $score) { // Get key and value
//$score_sub = array_slice($score,0,$hole); // Get the scores subset, first iteration is always all holes
$total_score = (string)$score[$hole-1]; // Get the key
if(!isset($positions[$total_score])){
$positions[$total_score] = array(); // Make array
}
$positions[$total_score][] = $golfer; // Add Golpher to score.
}
ksort($positions, SORT_NUMERIC); // Sort based on key, low -> high
return [
"winner"=> end($positions),
"score" => key($positions),
"tiebreaker_hole" => [
"hole"=>$hole,
"score"=> key($positions)],
]; // The last shall be first
}
//Recursion is Awsome
function getWinner(&$golfers, $hole = 9){
if ($hole == 0) return;
$highest = get_winners($golfers,$hole); // Get all ties, if any.
$winner = $highest;
if(count($winner["winner"]) > 1){ // If theirs ties, filter again!
$sub_golfers =
array_intersect_key($golfers,
array_flip($winner["winner"])); // Only the Worthy Shall Pass.
$winner = getWinner($sub_golfers,$hole - 1); // And again...
}
$winner["score"] = $highest["score"];
return $winner; // We got a winner, unless they really tie...
}
echo "<pre>";
print_R(getWinner($golfers));
echo "</pre>";
Result:
Array
(
[winner] => Array
(
[0] => 79
)
[score] => 18
[tiebreaker_hole] => Array
(
[hole] => 6
[score] => 14
)
)

Sort multidimensional array (PHP) - date complications and counting

I have the following output of an array using PHP. I need to do two things... First, I need to sort the array so it prints by the most recent date. I can't use a simple sort, because the date is outputted in the format mm/dd/yyyy (and not a regular time stamp) ...
Then I need to count how many rows exist for each year.
So, in the example below, I would need to know that there are ...
2 entries from 2010
2 entries from 2011
1 entry from 2012
Stop counting when there are no more rows
Since the year is not separate from the rest of the date digits, this also complicates things...
Array
(
[0] => Array
(
[racer_date] => 11/15/2010
[racer_race] => Test Row 4
[racer_event] => 321
[racer_time] => 16
[racer_place] => 12
[racer_medal] => 1
)
[1] => Array
(
[racer_date] => 7/15/2010
[racer_race] => Test Row 3
[racer_event] => 123
[racer_time] => 14
[racer_place] => 6
[racer_medal] => 0
)
[2] => Array
(
[racer_date] => 7/28/2011
[racer_race] => Test Row
[racer_event] => 123
[racer_time] => 10
[racer_place] => 2
[racer_medal] => 2
)
[3] => Array
(
[racer_date] => 10/9/2011
[racer_race] => Test Row 2
[racer_event] => 321
[racer_time] => 12
[racer_place] => 3
[racer_medal] => 3
)
[4] => Array
(
[racer_date] => 10/3/2012
[racer_race] => World Indoor Championships (final)
[racer_event] => 400m
[racer_time] => 50.79
[racer_place] => 1
[racer_medal] => 1
)
)
function cmp($a, $b)
{
if (strtotime($a["racer_date"]) == strtotime($b["racer_date"])) {
return 0;
}
return (strtotime($a["racer_date"]) < strtotime($b["racer_date"])) ? -1 : 1;
}
usort($array, "cmp");
call your array $array, and above code will sort it..
And to count entities you'll need to run foreach and check date('Y',strtotime($a["racer_date"])) in that foreach which will give you year in 4 digit..

PHP: Determine number of characters that come before a dash in a string

If I have a bunch of strings like XXX-WYC-5b, where XXX is any value between 1 and 999, how do I determine the length of XXX?
So I might have:
1: 6-WYC-5b
2: 32-WYC-5b
3: 932-W-5b
4: 22-XYQ-5b
5: 914-WYC-5b
And I want it to tell me the length of XXX, so:
1: 1 character
2: 2 characters
3: 3 characters
4: 2 characters
5: 3 characters
I would also like to know the value itself, so:
1: 6
2: 32
3: 932
4: 22
5: 914
I keep thinking there's a way to do this using substr_count() and explode(), but I can't seem to figure it out. Thanks very much for your help.
Use PHP's built-in string position function. Because it starts counting at 0, you don't even have to adjust the output:
$pos = strpos($string, "-");
For the second part, use PHP's substring function:
return substr($string, 0, $pos);
a different approach you may want to try:
<?php
$str[] = '6-WYC-5b';
$str[] = '32-WYC-5b';
$str[] = '932-W-5b';
$str[] = '22-XYQ-5b';
$str[] = '914-WYC-5b';
foreach($str as $v){
$result[] = getval($v);
}
function getval($value){
$seg = explode('-',$value);
return array('int'=>$seg[0],'intlen'=>strlen($seg[0]),'char'=>$seg[1],'charlen'=>strlen($seg[1]),'last'=>$seg[2],'lastlen'=>strlen($seg[2]));
}
print_r($result);
?>
outputs:
Array
(
[0] => Array
(
[int] => 6
[intlen] => 1
[char] => WYC
[charlen] => 3
[last] => 5b
[lastlen] => 2
)
[1] => Array
(
[int] => 32
[intlen] => 2
[char] => WYC
[charlen] => 3
[last] => 5b
[lastlen] => 2
)
[2] => Array
(
[int] => 932
[intlen] => 3
[char] => W
[charlen] => 1
[last] => 5b
[lastlen] => 2
)
[3] => Array
(
[int] => 22
[intlen] => 2
[char] => XYQ
[charlen] => 3
[last] => 5b
[lastlen] => 2
)
[4] => Array
(
[int] => 914
[intlen] => 3
[char] => WYC
[charlen] => 3
[last] => 5b
[lastlen] => 2
)
)

Categories