简体   繁体   English

如何在逗号分隔的文件中插入逗号

[英]How to insert comma in comma separated file

I am creating a comma separated file using a data array in a loop. 我正在循环中使用数据数组创建逗号分隔的文件。 But the problem is that if any location in the array already has a comma then it does not create a correct comma separated file. 但是问题是,如果数组中的任何位置已经有逗号,那么它不会创建正确的逗号分隔文件。

How do I include a string with a comma in comma separated file. 如何在逗号分隔的文件中包含带逗号的字符串。

Thanks 谢谢

Put qoutation marks ( " ) around the string. If you also have " in the string, escape those by doubling. 在字符串周围放置qoutation标记( " )。如果字符串中也包含”“,则将其加倍以将其转义。 Example row: 示例行:

"hello world, I'll call you ""Earth""", 4, 2, "another string"

So, if you have a string in the variable $field, normalize the field in this fashion: 因此,如果变量$ field中有一个字符串,请按照以下方式规范化该字段:

$field = '"'. str_replace('"', '""', $field) .'"';

The usual way is to quote the field: 通常的方法是引用该字段:

id,name,position
1,"Maxwell, Sam",CTO
2,Bob,Techie

This depends on what program will be reading the file. 这取决于要读取文件的程序。

If the parser is written as a state machine, commas should not be handled as delimiters when the string has quotes around it. 如果解析器是作为状态机编写的,则当字符串周围带有引号时,不应将逗号作为定界符处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM