查找自动换行并取消自动换行


PHP Find word wrapped lines and unwordwrap

我有这个输出(来自另一个系统),我需要将Test字段放在一行上。这个愚蠢的系统以45个字符换行(每行前有30个空格)

这是我的输出示例(我需要输入)

                      Name:
                      Pepsi
                      Test:
                      The Result was blah
                      and blah
                      Tester:
                      John
                      Name:
                      Sprite
                      Test:
                      The result was negative
                      Tester:
                      Jane
                      Etc etc

有时Test:后面的行会换行(有时不会)
我需要这行取消换行这样我就可以在access中导入了

该文件大约有2mb,并且有很多实例需要清理。这就是为什么我试图写这个脚本。

由于

---------------- 编辑 -------------

这是我到目前为止所想到的。但是我不能用它来代替

<?php
function replace_newline($string) {
    return (string)str_replace(array("'r", "'r'n", "'n", "     ", "    ", "   ", "  "), ' ', $string);
}
function GetBetween($content,$start,$end){
    $r = explode($start, $content);
    foreach($r as $value){

        $t = explode($end, $value); //$t[0] between value
        $result = trim(preg_replace('/['t'r'n]+/', ' ', trim($t[0])));
        $result = trim($result);
        $result = replace_newline($result);
        if ( !strstr($result, "Name:") ) {
            echo $result . "'r'n";
            $test = str_replace($t[0], $result, $test);
        }
    }

}
$test= file_get_contents("4321.txt");
GetBetween($test, "Test:", "Tester:");
?>
这个输出

:
结果是废话连篇
结果为阴性

这可能不是工作代码,但是您可以理解:

$cur = "";
foreach ($line as $l)
{
    if (strpos($l, ':') !== FALSE)
    {
        // Keep track of a new chunk
        if ( !empty(trim($cur)) ) { /* Write old data if not empty */ }
        // Start new chunk
        $cur = trim($l);
    }
    // Not a new chunk, add to end of last one
    $cur .= ' '. trim($l);
}
// Write the last chunk here
// Close file

你也许可以用一个疯狂的正则表达式块来完成整个事情,但我没有心情去做。


我知道我说过我不会使用正则表达式,但这里是:

function getChunks($data)
{
    // Clean up whitespace
    $data = preg_replace('/'s+/', ' ', $data);
    // Create an anchor point before the label word
    $data = preg_replace('/'w+:/', '##'0', $data);
    // Separate the data into chunks based on anchors
    $sets = explode('##', $data);
    // Keep any and all chunks that aren't empty
    $sets = array_filter($sets, function($d) { return !empty(trim($d)); } );
    // array_filter() can damage the indexing, so return just the values
    return array_values($sets);
}

我还没有测试代码,但是注释应该是一些指导。
请注意,这只适用于以下情况:1)只有标签包含分号,2)标签只有一个单词长。此外,您不会希望在海量数据集上运行此操作。它并没有针对这类事情进行优化。