2017-10-21 74 views
0

我几乎想从preg_match_all所有返回值分开,有3个值。注意:未定义偏移量:10,即使数组键数匹配?

我们得到的一切强大的标签内,数到一个数组,文本到另一个,和一切强大的标签后,进入第三,但我不断收到这个错误,我不想忽略。

这是通知:Notice: Undefined offset: 10 on line 49,它是$saveExtra = $matches[2][$key];一直在代码的底部。

$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; 
      } 

     } 
    } 
} 

如果我们print_r($arr_amount, $unit_id, $matches[2]),我们得到:

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 
) 

我一直在为这个在过去的2天没有能够找出为什么我不断收到未定义当$key是匹配,以抵消当前的迭代。

我已经把上的eval的代码时,https://eval.in/883856

+0

每当我'preg_match_all'玩我倾向于通过匹配设置,而不是默认使用'PREG_SET_ORDER'标志将它们分组'PREG_PATTERN_ORDER' – Scuzzy

+1

您正在寻找在'$ arr_units'更多的单位(11项),比在模式匹配'$比赛[2]'(10项) – Scuzzy

+0

我看到的,只是注意到没有[4]前两个键项目。 – Craig

回答

0

$match$match[2])的第三个项目是具有10个项目的阵列。 PHP数组具有从零开始的索引。

从我的观察,$key在某些时候等于10

$match[2]访问$key之前对这个附加保护条款,像这样:

if($key >= count($matches[2])) continue; 
+0

感谢您的帮助。 – Craig