代码之家  ›  专栏  ›  技术社区  ›  sprugman

字符串分析帮助

  •  0
  • sprugman  · 技术社区  · 15 年前

    我有一根这样的绳子:

    ####################
    Section One
    ####################
    Data A
    Data B
    
    
    ####################
       Section Two
    ####################
    Data C
    Data D
    
    etc.
    

    我想把它解析成如下内容:

    $arr(
        'Section One' => array('Data A', 'Data B'),
        'Section Two' => array('Data C', 'Data D')
    )
    

    起初我尝试过:

    $sections = preg_split("/(\r?\n)(\r?\n)#/", $file_content);
    

    问题是,文件不是完全干净的:有时节之间有不同数量的空行,或者数据行之间有空格。

    截面头部模式本身似乎相对一致:

    ####################
       Section Title
    ####################
    

    数字可能是一致的,但我不想指望它。标题行上的空白非常随机。

    一旦我把它分成几部分,我想这会很简单,但任何帮助写一个杀手注册前,以获得它在那里将是感激。(或者如果有比注册前更好的方法…)

    2 回复  |  直到 15 年前
        1
  •  1
  •   polygenelubricants    15 年前

    我很快就写下了:

    <?php
    $text = <<<EOT
    ####################
    Section One
    ####################
    Data B.Thing=bar#
    .##.#%#
    
    ####################
       Empty Section!
    ####################
    ####################
       Last section
    ####################
    
    Blah
    
       Blah C# C# C#
    
    EOT;
    $entries = array_chunk(
       preg_split("/^#+/m", $text, null, PREG_SPLIT_NO_EMPTY),
       2
    );
    $sections = array();
    foreach ($entries as $entry) {
      $key = trim($entry[0]);
      $value = preg_split("/\n/", $entry[1], null, PREG_SPLIT_NO_EMPTY);
      $sections[$key] = $value;
    } 
    print_r($sections);
    ?>
    

    输出为:( as run on ideone.com )

    Array
    (
        [Section One] => Array
            (
                [0] => Data B.Thing=bar#
                [1] => .##.#%#
            )
    
        [Empty Section!] => Array
            (
            )
    
        [Last section] => Array
            (
                [0] => Blah
                [1] =>    Blah C# C# C#
            )
    
    )
    
        2
  •  3
  •   salathe    15 年前

    我会采取多步骤的方法:

    • 分成章节标题/内容
    • 将每个标题/内容对解析为所需的数组结构

    下面是一个例子,分成多行,这样您就可以跟踪正在发生的事情:

    注意缺乏健全的检查,这是 假设 标题/内容组漂亮、整洁。
    regex是为简洁而编写的,可能不足以满足您的需要。

    // Split string on a line of text wrapped in lines of only #'s
    $parts = preg_split('/^#+$\R(.+)\R^#+$/m', $subject, null, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
    // Tidy up leading/trailing whitespace for each heading/content-block
    $parts = array_map('trim', $parts);
    // Chunk into array("heading", "content")
    $parts = array_chunk($parts, 2);
    
    // Create the final array
    $sections = array();
    foreach ($parts as $part) {
        $sections[$part[0]] = explode("\n", $part[1]);
    }
    
    // Lets take a look
    var_dump($sections);