dongsheng4679 2018-06-28 11:14
浏览 62
已采纳

如何使用php获取提交表单中的密钥部分

we have a form in which input added dynamically . In form submit page we will get the following result

print_r($_POST)

['wind_1']=hk
['wind_2']=pop
etc etc 

['wind_25']=another

so here we need to get the last key number , that is wind_n , here n=25

here the last input is ['wind_25'] that's why n=25

Please help .

  • 写回答

4条回答 默认 最新

  • dqc18251 2018-06-28 12:40
    关注

    Using regex seems unnecessary here unless you need to perform fullstring validation.

    It seems that you are only checking the static leading characters, so strpos() is the most efficient call.

    I am saving each found key instead of using a counter.

    When the loop finishes, I extract the integer from the last key.

    Code: (Demo)

    $_POST = [
        'wind_1' => 'hk',
        'hamburger_66' => 'foo',
        'wind_2' => 'pop',
        'wind_25' => 'another'
    ];
    
    foreach ($_POST as $k => $v) {
        if (strpos($k, 'wind_') === 0) {  // simple validatation
            $key = $k;  // overwrite previous qualifying key
        }
    }
    echo filter_var($key, FILTER_SANITIZE_NUMBER_INT);  // isolate the number
    // or you could use str_replace('wind_', '', $key);
    

    Or if you want to get a bit funky...

    echo max(preg_replace('~^(?:wind_|.*)~', '', array_keys($_POST)));
    

    This replaces all of the leading wind_ substrings OR the whole string, then plucks the highest value.

    Demo


    P.S. When you are anyone else ascends to PHP7.3 or higher, there is a wonderful function released (array_key_last())to access the last key of an array. (I'm assuming the keys are reliably structured/sorted.)

    Code: (Demo)

    $_POST = [
        'wind_1' => 'hk',
        'wind_2' => 'pop',
        'wind_25' => 'another'
    ];
    
    echo substr(array_key_last($_POST), 5);
    // output: 25
    

    After all of the above workarounds, I think the best advice would be to change the way you are coding your form fields. If you change the name attribute from wind_# to wind[#], you will create a wind subarray within $_POST and then you can access the number values without dissecting a string. (Demo)

    echo array_key_last($_POST['wind']);
    

    or (sub PHP7.3)

    end($_POST['wind']);
    echo key($_POST['wind']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?