Reputation: 658
I am capturing some data after taking a user through a number of steps. This data is successfully being captured in the below String format. Note that due to some limitations, I don't have an option to get this data in any other format.
There are two counts that are being captured. One is a Lap and then within each lap, the number of Reps.
Lap 1 Rep 1, 11, Lap 1 Rep 2, 12, Lap 1 Rep 3, 15, Lap 2 Rep 1, 22, Lap 2 Rep 2, 24, Lap 2 Rep 3, 29
I need to get the below values from the above code in a PHP Array.
Please note that since the user selected the number of Laps and Reps in the process, therefore Laps and Reps can go to double-digit as well. But when I am getting the above values, I have the total count of Laps and Reps as well. Like in the above example, I also have the Laps being 2 and Reps of each Lap being 3.
Can anyone help?
Upvotes: 2
Views: 93
Reputation: 13128
Like stated in the comments, you're best to run a regex query (using this as an example: Lap \d Rep \d, (\d+)
):
preg_match_all("/Lap \d Rep \d, (\d+)/", $str, $matches);
Now if you look at $matches[1]
, you'll get the following:
Array (
[0] => 11
[1] => 12
[2] => 15
[3] => 22
[4] => 24
[5] => 29
)
$str
being the string you have there as an example.
Upvotes: 4
Reputation: 14313
This will accomplish what you want. I first split the string by using the explode function, then I only keep every other element by using the mod function and checking the value to see if it is 0:
$info = "Lap 1 Rep 1, 11, Lap 1 Rep 2, 12, Lap 1 Rep 3, 15, Lap 2 Rep 1, 22, Lap 2 Rep 2, 24, Lap 2 Rep 3, 29";
$i = 1;
$keepThese = Array();
foreach(explode(", ", $info) as $value) {
if ($i++ % 2 == 0) {
array_push($keepThese, $value);
}
}
var_dump($keepThese);
PSST: You forgot 15 in your example output.
Upvotes: 3