在PHP中读取文件时,仅从段落的开头删除空格

时间:2018-01-09 07:16:50

标签: php file-handling removing-whitespace

朋友您好我正在阅读一个文件夹,其中我有许多PHP文本文件,我需要删除文本文件中每个段落开头的所有空格。但是当我正在阅读文件并尝试删除空间时,它不能正常工作,就像我尝试 TRIM 功能 LTRIM 一样,并尝试了REGEX " / \ s + $ / " 但都没有用。但是当我使用REGEX时,这个" / \ s + /" 而不是" / \ s + $ /" 所有的空间。我只需要从段落的开头删除任何帮助请...以下是我正在尝试的代码..

if ($dh = opendir($folder_path)){
    while (($file = readdir($dh)) !== false) {
        $path_parts = pathinfo($file);
        if ($path_parts['extension'] === 'txt' && $file1 = fopen($folder_path . '/' . $file, "r")) {
            $cleanStr ="";
            while(!feof($file1)) {
                $line = trim(fgets($file1));
                if ( trim($line)!="" ){
                    $str = preg_replace("/\s+$/", " ", ltrim($line));
                    echo $str;die;
                }
            }
        }
    }
    echo "Process finished..." . PHP_EOL;
    closedir($dh);
}

2 个答案:

答案 0 :(得分:1)

使用/^\s+/匹配段落开头的空格。 E.g。

$str = preg_replace("/^\s+/", "", $line);

答案 1 :(得分:0)

几年前我使用类似的东西进行类似的任务 - 似乎工作正常,也许它可能有用 - 但是如果你不想编辑文件而不是简单地使用file_put_contents { {1}}

echo implode(PHP_EOL, $content );

测试脚本使用名为<?php /* find all files in chosen folder */ $col=glob( $folder_path . '\*.*' ); /* filter only text files for processing */ $col=preg_grep( '@(\.txt$)@i', $col ); /* Proceed if there are text files only */ if( !empty( $col ) ){ /* iterate through collection */ foreach( $col as $index => $filepath ){ /* read file contents into an array */ $lines=file( $filepath ); /* store altered lines in temp array */ $content=array(); /* trim the start of each line & store into temp array */ foreach( $lines as $line )if( !empty( $line ) )$content[]=ltrim( $line ); /* write content back to file */ file_put_contents( $filepath, implode( PHP_EOL, $data ) ); } echo "finito!"; } ?> 的单个文本文件,其中包含以下内容。

lorem.txt

上面的大多数行在开头都有空格或制表符

                                                                    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque suscipit lacus massa, in malesuada quam consectetur at. Proin fermentum augue vel purus pellentesque placerat. Nunc tincidunt mi ac est varius, id euismod est auctor. Mauris facilisis luctus justo tristique consectetur. Vestibulum tempus lacinia blandit. Praesent dui metus, aliquet ut velit vitae, suscipit volutpat tortor. Nunc dictum nunc sed nisi bibendum dictum id vitae lorem. Donec viverra eget odio in hendrerit. Mauris iaculis at eros at scelerisque. Suspendisse a consequat erat, in fringilla diam. Fusce vitae hendrerit lacus. Ut sed purus vel metus semper sagittis. Ut fermentum magna quis tempus scelerisque.

    Phasellus quis rhoncus sapien. Nulla bibendum sagittis metus. Praesent elementum ex augue, a ullamcorper velit consectetur in. Maecenas mollis neque eu massa feugiat rutrum. Sed eu aliquam nulla. Sed sit amet egestas eros. Donec commodo leo in pellentesque efficitur. Cras ornare dui iaculis ultricies lobortis. Vivamus vel tellus maximus, sodales odio quis, ultrices metus.

       Nullam vitae rhoncus justo, a congue turpis. Nulla facilisi. Nulla faucibus massa et arcu molestie dignissim. Maecenas aliquet posuere eros sit amet vehicula. Praesent quis arcu eros. Quisque vitae dictum orci. Integer quis mollis felis.

    Morbi vitae risus fringilla, ornare ipsum ac, tincidunt metus. Ut ac eros placerat, auctor metus non, sollicitudin metus. Aenean malesuada gravida dolor, sit amet blandit lacus dignissim at. In egestas nibh felis, pulvinar laoreet eros rhoncus quis. Donec pulvinar condimentum ex, quis faucibus massa placerat sed. Fusce in mattis sem, sed rutrum nibh. Donec vitae risus urna. Suspendisse potenti. Maecenas vitae neque tempus, malesuada dolor et, rhoncus orci.

Duis quis augue vitae sapien cursus suscipit. Nulla rutrum eget diam in feugiat. Vestibulum posuere dapibus nisl at laoreet. Donec ante arcu, euismod et finibus ut, malesuada sed augue. Nunc porttitor leo ex, eget luctus augue sollicitudin non. Proin nec cursus ipsum. Nulla mi enim, finibus a felis vitae, pharetra tempor tortor. Proin a arcu lectus.

只需将变量<?php $folder_path='c:/wwwroot/content/stack'; $trim='rtrim'; /* find all files in chosen folder */ $col=glob( $folder_path . '\*.*' ); /* filter only text files for processing */ $col=preg_grep( '@(\.txt$)@i', $col ); /* Proceed if there are text files only */ if( !empty( $col ) && count( $col ) > 0 ){ /* iterate through collection */ foreach( $col as $index => $filepath ){ /* read file contents into an array */ $lines=file( $filepath ); /* store altered lines in temp array */ $content=array(); /* trim the start of each line & store into temp array */ foreach( $lines as $line )if( !empty( $line ) ){ $content[]=$trim( $line ); } /* write content back to file */ #file_put_contents( $filepath, implode( PHP_EOL, $data ) ); echo "<pre>" . implode( PHP_EOL, $content ) . "</pre>"; } printf( "finito! %d files processed",count( $col ) ); } else { echo "nothing to process"; } ?> $trim更改为rtrim,输出就会如预期一样

以下内容修改原始文件(不知道是否存在问题)并从cmdline运行 - 删除了行开头的所有空格。

ltrim