Php 如何使用字符串函数清除数组变量

Php 如何使用字符串函数清除数组变量,php,html,string,mysqli,Php,Html,String,Mysqli,我有这个php代码用于htmlform if(isset($_POST['job_title'])){ foreach($_POST['job_title'] as $selected) { $job_title[] = $selected ; } $job_title = json_encode($job_title); $job_title = clean_string($job_title); } 这就是清理SQL输入的clean\u字符串函数代码 functi

我有这个php代码用于html
form

if(isset($_POST['job_title'])){
  foreach($_POST['job_title'] as $selected) {
     $job_title[] = $selected ;
  }
  $job_title = json_encode($job_title);
  $job_title = clean_string($job_title);
}
这就是清理SQL输入的
clean\u字符串
函数代码

function clean_string($string){
   global $connection;
   $string = trim($string);
   $string = stripslashes($string);
   $string = htmlspecialchars($string);
   $string = htmlentities($string);
   $string = mysqli_real_escape_string($connection,$string);
   return $string;
}
因此,当执行此代码时,会导致如下错误( 要求参数1为字符串,数组给定

如何解决这个问题?
提前感谢

山姆大叔可能会说,这是你最有可能想做的:

<?php

    if(isset($_POST['job_title'])){
        foreach($_POST['job_title'] as $selected) {
            $job_title[] = clean_string($selected);
        }
        $job_title  = json_encode($job_title);
    }


    function clean_string($string){
        global $connection;
        $string = trim($string);
        $string = stripslashes($string);
        $string = htmlspecialchars($string);
        $string = htmlentities($string);
        $string = mysqli_real_escape_string($connection,$string);
        return $string;
    }

从您发布的内容来看,自定义函数clean\u string($string)接受字符串参数并返回字符串

您有一个数组$job\u title,需要对其进行清理

您面临的问题是,您正在将JSON传递给此行中的clean_string($string):

  $job_title = json_encode($job_title);
  $job_title = clean_string($job_title);  // JSON object is passed.
因此,只需遍历数组$job\u title中的每个元素,并将每个值传递给clean\u string()。这可以通过使用


问题是你想用这种消毒方法阻止什么?为什么要使用
htmlspecialchars
htmlentities
?一般来说,全局清理功能是合适的。您的POST数据包含哪些内容?尝试打印($\u POST)此变量将插入数据库,因此我尝试清理特殊字符以提高安全性@Script47POST数据包含正常数据!这个问题是因为我试图在数组上使用字符串函数,所以我想知道是否有办法解决这个问题@ObjectManipulator@MustafaAlsuhaibi那么,准备好的陈述就是所需要的。就目前的情况而言,您不知道要停止什么。是的,代码以前是这样的,但我认为最好在使用
json\u encode
之后再使用它!那么在
json\u encode
之前使用它就足够了吗@Poiz@MustafaAlsuhaibi绝对地如果您需要在数组上使用它,您可以按照更新后的帖子,该帖子使用了您删除的
json\u encode
,我更需要它,因为
$post['job\u title']
包含我需要对其进行
json_编码
json_解码
的多个值。在这种情况下,您可以在应用clean_string函数后应用json_编码。
  $job_title = json_encode($job_title);
  $job_title = clean_string($job_title);  // JSON object is passed.
if (isset($_POST['job_title'])) {
    foreach ($_POST['job_title'] as $selected) {
        $job_title[] = $selected ;
    }
    $job_title = array_map("clean_string", $job_title);  // Modify this line
    $job_title = json_encode($job_title);  // Add it here if you need to json encode the sanitized input
}