【问题标题】:Remove " from string in array从数组中的字符串中删除“
【发布时间】:2016-11-21 15:29:55
【问题描述】:

我有一个 HTML 表单,我需要将其存储在 DB 中,然后将其写入 .csv 和 .txt 。一切正常,除了 txt 输出给了我一些错误的字符串。

fputcsv 函数:

private function fputcsv_custom1($fp, $array, $eol)
{
  fputcsv($fp, $array, ';');
  if ("\r\n" != $eol && fseek($fp, -1, SEEK_CUR) === 0) 
  { fwrite($fp, $eol . "\r\n"); }
}

控制器:

$peoples = OnlineSz::all()->toArray();

$file = fopen("online_hotel.csv", "w+");
$file1 = fopen("online_hotel.txt", "w+");

array_keys($peoples);

foreach ($peoples as $key => $array) {
  $this->fputcsv_custom($file, $array, ';');
  $this->fputcsv_custom1($file1, $array, ';');
}
fclose($file);
fclose($file1);

它生成我 2 个文件,由 ; 分隔最后一个值给新行一个 \r\n。

txt输出是下一个:

53;"New test";Worker;test;test;4000;test;test;06123456789;test;0;0;CC;;0;0;

如果字符串包含空格,它是由 " " 存储的,我怎样才能删除这个引号?或者我怎样才能只替换数组中这一列的引号?

感谢您的帮助!

编辑

如果我替换 2 个单词之间的空格,引号不存在,但是如果我需要字符串之间的空格,我该怎么办?

控制器:

$this->fputcsv_custom($file4, str_ireplace(chr(32), '/',$user), ';');
$this->fputcsv_custom1($file5, str_ireplace(chr(32), '/',$user), ';');

输出:

53;New/test;Alkalmazott;test;test;4000;test;test;06123456789;0;0;CC;0;0;

但我错了,因为 /,如果我将其替换为 chr(32),引号将在那里。

有什么办法吗?

【问题讨论】:

    标签: php mysql laravel fputcsv


    【解决方案1】:

    使用 str_ireplace 删除引号....

    $var  = str_ireplace('"', '', $var); //strip quotes from $var
    
    
    
     $this->fputcsv_custom($file, str_ireplace('"', '',$array), ';');
     $this->fputcsv_custom1($file1, str_ireplace('"', '',$array), ';');
    

    您可能还想修剪它们的尾随空格....

     $this->fputcsv_custom($file, trim(str_ireplace('"', '',$array)), ';');
     $this->fputcsv_custom1($file1, trim(str_ireplace('"', '',$array)), ';');
    

    【讨论】:

    • 我已经使用了你的第一个答案,但在 .txt 中,引号仍然存在..
    • ? " Odd.. 也许复制你看到的字符并将其粘贴到 str_ireplace('X' 它可能不是标准引号
    • 已复制,但仍在输出 TXT 文件中
    【解决方案2】:

    您可以使用implode(";",$array);fputs(...) 而不是fputcsv(...)

    但请记住,csv php 函数遵循某个 RC 标准,我现在无法在 Google 上搜索。我稍后会编辑答案。所以你不再遵循标准了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 2019-04-15
      • 2011-05-06
      • 2017-02-10
      • 1970-01-01
      • 2013-03-02
      • 1970-01-01
      相关资源
      最近更新 更多