简体   繁体   English

php regex 用于多行的制表符和大写字母到 csv 字符串

[英]php regex for multiple lines with tabs and caps to csv string

I have several text files in the format我有几个格式的文本文件

CATEGORYA[can be multiple words but all caps] 
[tab]Item11[multiple upper/lower case words with spaces&numbers],$3.99
[tab]Item12,$7.49[the prices sometimes don't have the $]
etc.
[new line]
CATEGORYB[can be multiple words but all caps] 
[tab]Item21,$3.99
[tab]Item22,$7.49
etc.

I would like to convert it to a csv file in the format我想将其转换为格式的 csv 文件

 CATEGORYA,Item11,$3.99
 CATEGORYA,Item12,$7.49
 etc.
 CATEGORYB,Item21,$3.99
 CATEGORYB,Item22,$7.49
 etc.

this is the code i started with这是我开始的代码

//import file
$file = file_get_contents('./20051019.txt', true);
//split each category into an array
$catarray = preg_split("[regex of somesort]", $file);
//get number array elements
$numcats=count($catarray)
for ($x = 0; $x < $numcats; $x++)
{
//split the category from the elements
//loop through the elements replacing the tab with the category and a comma
//add element to a string
}
//write string out to a file

Can someone please help with the regex or know a better way to do this?有人可以帮助使用正则表达式或知道更好的方法吗?

//import file
$file = file_get_contents('./20051019.txt', true);
//split each category into an array
$catarray = preg_split("/(\n\n|\r\r|\r\n\r\n)/m", $file);
//get number array elements
$numcats=count($catarray)
//output string
$csvstring="";
for ($x = 0; $x < $numcats; $x++)
{
    $curline=$catarray[$x];
    $elements= preg_split("/[\n\t]/", $curline);
    $numitems= count($elements);
    $cat =trim($elements[0]);
    for ($y = 1; $y < $numitems; $y++)
    {
      $csvstring=$csvstring.$cat.",".trim($elements[$y])."\n";
    }
}
//write string out to a file

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

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