如何在php中修剪数组值的空格
Posted
技术标签:
【中文标题】如何在php中修剪数组值的空格【英文标题】:How to trim white spaces of array values in php 【发布时间】:2011-08-11 08:54:07 【问题描述】:我有一个数组如下
$fruit = array(' apple ','banana ', ' , ', ' cranberry ');
我想要一个数组,其中包含两边没有空格的值,但它可以包含空值如何在 php 中执行此操作。输出数组应该是这样的
$fruit = array('apple','banana', ',', 'cranberry');
【问题讨论】:
【参考方案1】:array_map 和 trim 可以完成这项工作
$trimmed_array = array_map('trim', $fruit);
print_r($trimmed_array);
【讨论】:
优秀。比使用 array_walk 或 foreach 循环简单得多 ravisoni,您将映射该函数;array_map('rtrim', $fruit);
。希望它有所帮助:)
这个更好 $fruit= array_map('trim', $fruit);
如果其中一个水果是一组 f.e. 会发生什么?异国水果?
@Halfacht 这不是递归函数,在这种情况下您必须编写自己的递归函数【参考方案2】:
array_walk()
可以与trim()
一起使用来修剪数组
<?php
function trim_value(&$value)
$value = trim($value);
$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);
array_walk($fruit, 'trim_value');
var_dump($fruit);
?>
见http://www.php.net/manual/en/function.trim.php的第二个例子
【讨论】:
【参考方案3】:多维证明方案:
array_walk_recursive($array, function(&$arrValue, $arrKey) $arrValue = trim($arrValue););
【讨论】:
谢谢!确认这一点实际上也会修剪嵌套内容,而不是忽略它们或set tonull
。【参考方案4】:
在使用多维数组时,我对现有答案有疑问。这个解决方案对我有用。
if (is_array($array))
foreach ($array as $key => $val)
$array[$key] = trim($val);
【讨论】:
【参考方案5】:如果数组是多维的,这会很好用:
//trims empty spaces in array elements (recursively trim multidimesional arrays)
function trimData($data)
if($data == null)
return null;
if(is_array($data))
return array_map('trimData', $data);
else return trim($data);
一个样本测试是这样的:
$arr=[" aaa ", " b ", "m ", [" .e ", " 12 3", "9 0 0 0 "]];
print_r(trimData($arr));
//RESULT
//Array ( [0] => aaa [1] => b [2] => m [3] => Array ( [0] => .e [1] => 12 3 [2] => 9 0 0 0 ) )
【讨论】:
【参考方案6】:如果你想修剪和打印一维数组或多维数组的最深维度,你应该使用:
foreach($array as $key => $value)
$array[$key] = trim($value);
print("-");
print($array[$key]);
print("-");
print("<br>");
如果您想修剪但不想打印一维数组或多维数组的最深维度,您应该使用:
$array = array_map('trim', $array);
【讨论】:
【参考方案7】:$fruit= array_map('trim', $fruit);
【讨论】:
这只是the accepted answer的重复。【参考方案8】:array_map('trim', $data)
会将所有子数组转换为null
。如果只需要为字符串修剪空格,其他类型保持不变,可以使用:
$data = array_map(
function ($item)
return is_string($item) ? trim($item) : $item;
,
$data
);
【讨论】:
【参考方案9】:如果您不想丢失关联数组的元素,请不要使用array_walk
或array_map
!
foreach 解决方案的略短版本:
foreach($array as &$val)
$val = trim($val);
这适用于关联数组。
【讨论】:
【参考方案10】:function generateRandomString($length = 10)
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++)
$randomString .= $characters[rand(0, $charactersLength - 1)];
return $randomString;
function generateRandomSpaces()
$output = '';
$i = rand(1, 10);
for ($j = 0; $j <= $i; $j++)
$output .= " ";
return $output;
// Generating an array to test
$array = [];
for ($i = 0; $i <= 1000; $i++)
$array[] = generateRandomSpaces() . generateRandomString(10) . generateRandomSpaces();
// ARRAY MAP
$start = microtime(true);
for ($i = 0; $i < 100000; $i++)
$trimmed_array=array_map('trim',$array);
$time = (microtime(true) - $start);
echo "Array map: " . $time . " seconds\n";
// ARRAY WALK
$start = microtime(true);
for ($i = 0; $i < 100000; $i++)
array_walk($array, 'trim');
$time = (microtime(true) - $start);
echo "Array walk : " . $time . " seconds\n";
// FOREACH
$start = microtime(true);
for ($i = 0; $i < 100000; $i++)
foreach ($array as $index => $elem)
$array[$index] = trim($elem);
$time = (microtime(true) - $start);
echo "Foreach: " . $time . " seconds\n";
// FOR
$start = microtime(true);
for ($i = 0; $i < 100000; $i++)
for ($j = 0; $j < count($array) - 1; $j++)
$array[$j] = trim($array[$j]);
$time = (microtime(true) - $start);
echo "For: " . $time . " seconds\n";
上面代码的输出是:
数组映射:8.6775720119476 秒 阵列步行:10.423238992691 秒 Foreach:7.3502039909363 秒 对于:9.8266389369965 秒
这个值当然可能会改变,但我会说 foreach 是最好的选择。
【讨论】:
所有这些代码和文本中是否有原始问题的答案?【参考方案11】:如果值是 NULL,则修剪 array_map 更改类型。
更好的方法:
$result = array_map(function($v)
return is_string($v)?trim($v):$v;
, $array);
【讨论】:
【参考方案12】:您只需使用正则表达式来修剪所有空格或缩小您的数组项
$array = array_map(function ($item)
return preg_replace('/\s+/', '', $item);
, $array);
【讨论】:
【参考方案13】:function trim_value(&$value)
$value = trim($value);
// ut_sreco_dis Module
public function disExcelUpload($file="")
ini_set('MAX_EXECUTION_TIME', -1);
ini_set('memory_limit', '-1');
$file_upload = $file;
if (isset($file_upload) && !empty($file_upload))
//You can add directly the Composer Autoloder in your controller:
require FCPATH . 'vendor/autoload.php';
try
$objPHPExcel = PHPExcel_IOFactory::load($file_upload);
catch (Exception $e)
die('Error loading file "' . pathinfo($file_upload, PATHINFO_BASENAME) . '": '.@$e->getMessage());
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
$highestco = $sheet->getHighestDataColumn();
$arrayCount = count($allDataInSheet);
$now = date("Y-m-d H:i:s");
$flag = 0;
$check_template = array(
'A' => 'FIN_ID',
'B' => 'SECCODE',
'C' => 'SCHEME_NO',
'D' => 'SEC_SCH',
'E' => 'DISNO',
'F' => 'DISQTY',
'G' => 'BILLQTY',
'H' => 'BILLREF',
'I' => 'BILLDT',
);
$input_template = $allDataInSheet[1];
array_walk($input_template, $this->trim_value);
$result = array_diff($check_template, $input_template);
if(empty($result))
$this->srObject->truncTableDis();
# loop for inserting data
for ($i = 2,$j=0; $i <= $highestRow; $i++)
$db_ch_ot = 64;
$fin_id = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_code = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sch_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_sch = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_ref = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_dt = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
if(empty($bill_dt))
$bill_dt = null;
else
$dip_dt = date("Y-m-d",strtotime($bill_dt));
$dt = date('Y-m-d H:i:s');
$insert_data = array(
"fin_id_data" => $fin_id,
"sec_code_data" => $sec_code,
"sch_no_data" => $sch_no,
"sec_sch_data" => $sec_sch,
"dis_no_data" => $dis_no,
"dis_qty_data" => $dis_qty,
"bill_qty_data" => $bill_qty,
"bill_ref_data" => $bill_ref,
"bill_dt_data" => $bill_dt,
"created_at_data" => $dt,
"updated_at_data" => $dt,
);
if($this->srObject->insertSdisData($insert_data))
++$flag;
//loop close
else
$this->session->set_flashdata('error', 'Error. Invalid Excel Template');
redirect(site_url('schill-bill-checking-suuti/sreco'));
$this->session->set_flashdata('success', 'File Uploaded Successfully ..'.' New Record Inserted : '.$flag);
redirect(site_url('schill-bill-checking-suuti/sreco'));
【讨论】:
【参考方案14】:function trim_value(&$value)
$value = trim($value);
// ut_sreco_dis Module
public function disExcelUpload($file="")
ini_set('MAX_EXECUTION_TIME', -1);
ini_set('memory_limit', '-1');
$file_upload = $file;
if (isset($file_upload) && !empty($file_upload))
//You can add directly the Composer Autoloder in your controller:
require FCPATH . 'vendor/autoload.php';
try
$objPHPExcel = PHPExcel_IOFactory::load($file_upload);
catch (Exception $e)
die('Error loading file "' . pathinfo($file_upload, PATHINFO_BASENAME) . '": '.@$e->getMessage());
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
$highestco = $sheet->getHighestDataColumn();
$arrayCount = count($allDataInSheet);
$now = date("Y-m-d H:i:s");
$flag = 0;
$check_template = array(
'A' => 'FIN_ID',
'B' => 'SECCODE',
'C' => 'SCHEME_NO',
'D' => 'SEC_SCH',
'E' => 'DISNO',
'F' => 'DISQTY',
'G' => 'BILLQTY',
'H' => 'BILLREF',
'I' => 'BILLDT',
);
$input_template = $allDataInSheet[1];
array_walk($input_template, $this->trim_value);
$result = array_diff($check_template, $input_template);
if(empty($result))
$this->srObject->truncTableDis();
# loop for inserting data
for ($i = 2,$j=0; $i <= $highestRow; $i++)
$db_ch_ot = 64;
$fin_id = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_code = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sch_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_sch = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_ref = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_dt = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
if(empty($bill_dt))
$bill_dt = null;
else
$dip_dt = date("Y-m-d",strtotime($bill_dt));
$dt = date('Y-m-d H:i:s');
$insert_data = array(
"fin_id_data" => $fin_id,
"sec_code_data" => $sec_code,
"sch_no_data" => $sch_no,
"sec_sch_data" => $sec_sch,
"dis_no_data" => $dis_no,
"dis_qty_data" => $dis_qty,
"bill_qty_data" => $bill_qty,
"bill_ref_data" => $bill_ref,
"bill_dt_data" => $bill_dt,
"created_at_data" => $dt,
"updated_at_data" => $dt,
);
if($this->srObject->insertSdisData($insert_data))
++$flag;
//loop close
else
$this->session->set_flashdata('error', 'Error. Invalid Excel Template');
redirect(site_url('schill-bill-checking-suuti/sreco'));
$this->session->set_flashdata('success', 'File Uploaded Successfully ..'.' New Record Inserted : '.$flag);
redirect(site_url('schill-bill-checking-suuti/sreco'));
【讨论】:
【参考方案15】:function trimArray(&$value)
$value = trim($value);
$pmcArray = array('php ','mysql ', ' code ');
array_walk($pmcArray, 'trimArray');
通过使用array_walk函数,我们可以从数组元素中删除空间,元素返回相同数组中的结果。
【讨论】:
以上是关于如何在php中修剪数组值的空格的主要内容,如果未能解决你的问题,请参考以下文章