Reputation: 593
I'm pretty much trying to separate all the returned values from preg_match_all, there are 3 values.
We get everything inside the strong tags, numbers into one array, text into another, and everything after the strong tags goes into the third, but I keep getting this error that I don't want to ignore.
This is the notice: Notice: Undefined offset: 10 on line 49
, and it's $saveExtra = $matches[2][$key];
all the way at the bottom of the code.
$html = "<strong>1 1/4 lb.</strong> any type of fish
<strong>3 tsp.</strong> tarragon
<strong>3 tsp.</strong> tomato sauce
<strong>1 tbsp.</strong> coconut oil
<strong>Pepper and Salt</strong>, it's optional
<strong>2 tbsp.</strong> oil
<strong>1/4 cup</strong> cream
<strong>1/4 tsp.</strong> tarragon
<strong>1/4 tsp.</strong> tomato sauce
<strong>Salt and Pepper</strong>, it's optional too
";
$variations = array('lb', 'tsp', 'tbsp', 'cup');
$setInfo = [];
$arr_amount = [];
$extra_arr = [];
$arr_units = [];
if(preg_match_all("/<(?:strong|b)>(.*)(?:<\/(?:strong|b)>)(.*)/", $html, $matches)) {
foreach($matches[1] as $amounts){
preg_match_all("/^(?:[\p{Pd}.\/\s-]*[\d↉½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑⅒⅟])+/um", $amounts, $amount);
preg_match_all('/[a-zA-Z :]+/m', $amounts, $unit);
foreach($amount[0] as $amount_arr){
$arr_amount[] = $amount_arr;
}
foreach($unit[0] as $units_rr){
$arr_units[] = trim(strtolower($units_rr));
}
$unit_id = array();
foreach($arr_units as $key => $unit_arr){
foreach($variations as $unit_var){
if(strtolower(trim($unit_arr)) == $unit_var){
$unit_id[] = $unit_var;
}
}
if(str_word_count($unit_arr) >= 2){
$arr_amount[$key] = '';
$unit_id[$key] = '';
$saveExtra = $matches[2][$key];
$matches[2][$key] = $unit_arr . $saveExtra;
}
}
}
}
If we print_r($arr_amount, $unit_id, $matches[2])
, we get:
Array
(
[0] => 1 1/4
[1] => 3
[2] => 3
[3] => 1
[5] =>
[6] => 2
[7] => 1/4
[8] => 1/4
[9] => 1/4
[10] =>
)
Array
(
[0] => lb
[1] => tsp
[2] => tsp
[3] => tbsp
[5] =>
[6] => tbsp
[7] => cup
[8] => tsp
[9] => tsp
[10] =>
)
Array
(
[0] => any type of fish
[1] => tarragon
[2] => tomato sauce
[3] => coconut oil
[4] => , it's optional
[5] => pepper and saltpepper and saltpepper and saltpepper and saltpepper and saltpepper and salt oil
[6] => cream
[7] => tarragon
[8] => tomato sauce
[9] => , it's optional too
[10] => salt and pepper
)
I've been at this for the past 2 days without being able to figure out why I keep getting undefined offset when the $key
is matching to that current iteration.
I've put the code up on eval, https://eval.in/883856
Upvotes: 0
Views: 373
Reputation: 38982
The third item in $match
(i.e $match[2]
) is an array with 10 items. PHP arrays have zero-based index.
From my observation, $key
at some point equals 10
.
Add a guard clause against this like so before accessing $key
in $match[2]
:
if($key >= count($matches[2])) continue;
Upvotes: 1