English 中文(简体)
• 如何从固定起用钥匙进入一个子系列的“POST”阵列
原标题:How to get a subset of $_POST array with keys starting with a prefix

Let s say my $_POST variable looks like:

<?php

Array
(
    [user_ID] => 65
    [action] => editpost
    [originalaction] => editpost
    [post_author] => 154
    [empl_bd_dd] => 6
    [empl_bd_mm] => 5
    [empl_bd_yy] => 1987
    [empl_gen] => 1
    [empl_height] => 155
    [empl_weight] => 61
    [empl_arra] => 2
    [save] => Update
    [post_it] => 2
    [empl_pay] => J77
    [empl_cust] => Married
    [empl_lang] => Array
        (
            [0] => EN
            [1] => FR
        )
    [empl_rent] => 1
    [name] => Jimmy Nathan
    [empl_text] => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sed interdum leo. Sed et elit quam, tempor placerat neque. Nullam sapien odio, egestas iaculis dictum ut, congue ullamcorper tellus.
    [empl_sk_0] => 6
    [empl_sk_1] => 7
    [empl_sk_2] => 5
)

?>

各位可以看到,我把我的所有形式变数预先定在<代码>empl_上。 没有必要逐一具体说明所有这些内容,我如何从<代码>_POST将所有形式变数输入一个成本最低的、希望可行的阵列? 是否有PHP阵列功能或组合,我可以加以利用?

与<代码>CSS一样,如果你能够选择使用<代码>>empl的类别的所有要素,则使用<代码>[类别*=”empl_>,那么,我就能够以这种方式与PHP的阵列钥匙,例如。

$empl_post = $_POST[ empl_* ]

<>strong>EDITED ANSWER - imptediation to @chris swer:$_POST must be the first debate to array_intersection_key, e.g:

$empl_POST = array_intersect_key($_POST, array_flip(preg_grep( /^empl_/ , array_keys($_POST))));
最佳回答
$r = array_intersect_key($_POST, array_flip(preg_grep( /^empl_/ , array_keys($_POST))));

<次>真正需要添加一个<代码>PREG_GREP_KEYS的旗号:preg_grep( 因此,我们不需要做所有东西......。

作为职能:

function preg_grep_keys($pattern, $input, $flags = 0) {
    return array_intersect_key(
        $input,
        array_flip(preg_grep(
           $pattern,
           array_keys($input),
           $flags
        ))
    );
}

Edit - since php 5.6 array_filter 现在有一些新的旗帜,使你能够进入过滤背中的关键阵列。

function preg_grep_keys($pattern, $input, $flags = 0) {
    return array_filter($input, function($key) use ($pattern, $flags) {
           return preg_match($pattern, $key, $flags);
    }, ARRAY_FILTER_USE_KEY);
}

用途

$filtered = preg_grep_keys( /^empl_/ , $_POST);
问题回答
function GetPrefixedItemsFromArray($array, $prefix)
{
    $keys = array_keys($array);
    $result = array();

    foreach ($keys as $key)
    {
        if (strpos($key, $prefix) === 0)
        {
            $result[$key] = $array[$key];
        }
    }

    return $result;
}

然后用<代码>$myArray = GetprefixedItemsFromArray($_POST,“empl_”);。

$empl_post = array();
foreach ($_POST as $k => $v) {
    if (strpos($k,  empl_ ) !== 0) continue;
    $empl_post[substr($k, 5)] = $v
}

print_r($empl_post);

另一种方法:

$formVars = $_POST;
foreach ($formVars as $key=>$value) {
    if (strpos($key,  empl_ )===false) 
        unset($formVars[$key]);
}

如果你想像这样的东西,

$keyPattern =  /^empl_*/ ;
$matching_array = getArrayElementsWithMatchingKeyPattern($_POST,$keyPattern);

Then I dont think there is an inbuilt way to that. Best way would be a foreach loop with a regex match.

function getArrayElementsWithMatchingKeyPattern($array,$keyPattern){
    $matching_array = array();

    foreach ($keyPattern as $k => $v) {
       if (preg_match($array[$k],$keyPattern) > 0)
             $matching_array[$k] = $v;
    }

    return ($matching_array);

}

此处采用冷静的超地点-内基办法,使用Sphp阵列-walk,具体指明一个通用的预设装置,以消除:

$foo = array( k_foo  =>"bar", 
               k_bar  =>"b0r", 
               y_foo  =>"b5r",
               y_not  =>"b7r", 
              k_not  =>"b1r");

$subsetArray = $foo;
$key_prefix = "k_";

array_walk($foo,  removeUnwanted , array(&$subsetArray, $key_prefix));
var_dump ($subsetArray);

function removeUnwanted($value, $key, $array){
    $prefix = $array[1];
    $testArray = &$array[0];
    if(strpos($key,$prefix) ===0){
        unset($testArray[$key]); 
    } 
}

现在,你只能说几条路,有一系列价值观的复印件,还有预设体。

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

然后用米阿雷=GetpretecedItemsFromArray(POST,“empl);

从PHP 5.6开始,你可以使用阵列——过滤器以及ARRAY_FILTER_USE_KEY。

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

在安全方面,您可根据您的需要,在过滤器_投入-通知功能上添加FIFLTER_SANITIZE_*,直接使用“POST”这一美元,过滤器_Input_array,没有第二个参数,则回落到FLTER_UNSAFE_RAW。





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签