如何从以下场景中的每个数组元素中删除\'?

时间:2013-10-13 05:15:35

标签: javascript php jquery ajax arrays

我正在使用jQuery从我的表单上的隐藏字段中获取值。这些值中的每一个都出现在单引号中,例如'enable'。现在,我正在创建一个数组并在其中推送这些值。我正在使用javascript将此数组发送到PHP文件。我通过jQuery AJAX方法的url attrubute发送这个数组。它的代码如下:

$(document).ready(function() {
  $(document).on('click', '#disable_url', function (e) {    
    e.preventDefault();

    var items = new Array();

    $("input:checked:not(#ckbCheckAll)").each(function() {
      items.push($(this).val());
    });

    var str = $("#user_filter").serialize();    
    var str = decodeURIComponent(str);

    var user_status = new Array();
    for (var i = 0; i < items.length; i++) {
      user_status.push($("#"+items[i]).val());
    }    

    $.ajax({
      type: "POST",
      url: "manage_users.php?op=disable_bulk_users&items="+items+"&options="+str+"&user_status="+user_status,
      dataType: 'json',  
      success: function(data) {
        var redirect_link = data.href;
        window.location.href = redirect_link;
      }          
    });
  })
});

现在manage_users.php的PHP代码片段如下:

$request = empty( $_GET ) ? $_POST : $_GET ;
  $op       = $request['op'];
  switch( $op ) {
    case "disable_bulk_users":
   /*I'm using explode here as I'm getting the comma separated list of strings and I want to convert it back into an array*/ 
    $user_ids = explode(',', $request['items']);
    $user_statuses = explode(',', $request['user_status']);
    print_r($user_statuses);
    die;
    break;
  }

如果我打印数组$user_statuses,则打印如下:

Array
(
    [0] => \'enable\'
    [1] => \'enable\'
    [2] => \'enable\'
    [3] => \'enable\'
    [4] => \'enable\'
    [5] => \'enable\'
    [6] => \'disable\'
    [7] => \'disable\'
    [8] => \'disable\'
    [9] => \'disable\'
    [10] => \'disable\'
    [11] => \'disable\'
    [12] => \'disable\'
    [13] => \'disable\'
    [14] => \'disable\'
    [15] => \'disable\'
    [16] => \'disable\'
    [17] => \'disable\'
    [18] => \'disable\'
    [19] => \'disable\'
)

实际上我想删除开头出现的字符串 \',并在每个数组元素的末尾删除字符串 \'。删除这些字符串后,你能帮助我获得干净的数组吗?提前谢谢。

4 个答案:

答案 0 :(得分:1)

试试这个:

function mytrim(&$item){
 $item = trim($item, "\'");
}
$array = array("\'test\'", "\'test2\'");

array_walk($array, "mytrim");
print_r($array);//Array ( [0] => test [1] => test2 )

答案 1 :(得分:1)

如果你想在客户端做这件事:

user_status.push($("#"+items[i]).val().replace(/'/g,''));

答案 2 :(得分:1)

在php中,

$data = array_map('stripslashes', $data);

或者如果你想删除引号

$data = array_map('trim', $data, ['\\\''])

答案 3 :(得分:0)

使用字符串替换消除字符串中的“\”。 $ status = str_replace(“\'”,'',$ user_statuses);