【问题标题】:php regex for multiple lines with tabs and caps to csv stringphp 正则表达式用于多行,带有制表符和大写到 csv 字符串
【发布时间】:2015-09-12 22:18:11
【问题描述】:

我有几个格式的文本文件

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.

我想把它转换成csv格式的文件

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

这是我开始的代码

//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

有人可以帮助使用正则表达式或知道更好的方法吗?

【问题讨论】:

  • 你已经有了正则表达式,你写了“几个带有空格和数字的大写/小写单词”。那,作为一个正则表达式,由(\w+\s+)*\w+ 表示。你只需要学习语言 (regular-expressions.info/tutorial.html)。在这里我们会在遇到问题时回答问题,而不是代替他们解决问题。
  • 我假设当您输入[new line] 时,实际上一行中有两行新行(即,一行包含内容,一行不包含内容,另一行包含内容)。如果是这种情况,请连续拆分两个新行,然后将每个“类别”再次拆分为新行。然后循环遍历所有内容。
  • $catarray = preg_split("/[\n\n]/", $file);不工作
  • 试试preg_split("/(\n\n|\r\r|\r\n\r\n)/gm", $file)
  • 警告:preg_split():未知修饰符“g”

标签: php regex file csv


【解决方案1】:
//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

【讨论】:

    猜你喜欢
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多