doupian9490 2011-04-13 17:43
浏览 35
已采纳

清理表单中的数组元素

I have a form that uses inputs to create and array. The inputs are not all required but at least one is.

<form method="post" action="process.php">
    <input type="text" name="MAC[]" maxlength="12" />
    <input type="text" name="MAC[]" maxlength="12" />
    <input type="text" name="MAC[]" maxlength="12" />
    <input type="text" name="MAC[]" maxlength="12" />
    <input class="submitbg" type="submit" value="Register" name="submit"/>
 </form>

Now on process.php I want to loop through the array remove two types of special characters : ; then make all upper case, and verify there are only 12 characters and then serialize the arrray.

$my_array = $_POST['MAC'];
foreach ($my_array as $val){
    $val = strtoupper($val);
    $val = str_replace(";","",$val);
    $val = str_replace(":","",$val);
    $val = trim($val);
    if (strlen($val) != 12)){
        $valid = false;
        $error = "Your MAC address is not 12 characters long";
    }
}
$mac_addresses = serialize($my_array);

// if valid is not false do something with the cleaned up array.

The questions:

  1. Will my foreach loop save the updated values back into the array?
  2. How to check to make sure there is at least one array value?
  • 写回答

4条回答 默认 最新

  • dpwdsmbvm496180204 2011-04-13 17:58
    关注
    1. What's the question?
    2. you can do str_replace(array(';',':'),'',$val);
    3. It's usually better to trim before doing other processing on the same variable due to the overhead involved in processing data you will eventually cut
    4. Consider using break on errors, if you halt execution on one error.
    5. You're not really doing any updates to $my_array.

    Consider doing:

    foreach($my_array as &$val)
    

    You pass by reference so all updates to $val happen to the actual array. Or:

    foreach($my_array as $key=>$val){
        $my_array[$key]=trim($my_array[$key]);
    

    You can also try to create a new array for your sanitized data and then over-write your old array. It all depends on needs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c