How to get a subset of $_POST array with keys starting with a prefix

前端 未结 8 1519
栀梦
栀梦 2020-12-31 13:18

Let\'s say my $_POST variable looks like:

 65
    [action] => editpost
    [originalaction] => editpo         


        
相关标签:
8条回答
  • 2020-12-31 14:17
    function GetPrefixedItemsFromArray($array, $prefix, $remplacePref=FALSE)    {
        $keys = array_keys($array);
        $result = array();
    
        foreach ($keys as $key) {
            if (strpos($key,$prefix) === 0) {
                if($remplacePref===TRUE){
                    $result[str_replace($prefix, "", $key)] = $array[$key];
                }
                elseif($remplacePref!==FALSE && $remplacePref!==""){
                    $result[str_replace($prefix, $remplacePref, $key)] = $array[$key];
                }
                else{
                    $result[$key] = $array[$key];
                }               
            }
        }
        return $result;
    }
    

    Then simply call with $myArray = GetPrefixedItemsFromArray($POST, "empl");.

    0 讨论(0)
  • 2020-12-31 14:17

    Starting from PHP 5.6 you can use array_filter along with the option ARRAY_FILTER_USE_KEY.

    $employee = array_filter(filter_input_array(INPUT_POST), function($key) {
      return strpos($key, 'empl_') === 0;
    }, ARRAY_FILTER_USE_KEY);
    

    For security concerns, you may add FILTER_SANITIZE_* to the filter_input_array function according to your needs, accessing $_POST directly is disadvised and filter_input_array without second parameter falls back to FILTER_UNSAFE_RAW.

    0 讨论(0)
提交回复
热议问题