开发者

Append text to lines in text document, using PHP

How do I append the following text to the start of new lines in a text document using PHP?

Line 1: T: my text here

Line 2: Z: my text here

Line 3: T: my text here

etc.

Basically, alter开发者_如何学编程nate between T: and Z:.

Assume I use explode of some sort? Thanks


Use file to get each line of the file. Then iterate each line, append your text and save the file using file_put_contents

<?php

$lines = file('input-file.txt');

$output = '';
$TorZ = 'T';
foreach ($lines as $line)
{
    $output .= $TorZ.': '.$line.PHP_EOL;

    if($TorZ == 'T')
        $TorZ = 'Z';
    else
        $TorZ = 'T';
}

file_put_contents('output.txt', $output);
?>


if it's in the file, use file() to read the file, you'll get array of lines. If it's a string, use explode("\n", $string). If you don't know the separator, you can use preg_split("/(\n|\r|\n\r)/", $string). Then loop over the elements of the array and prepend the string, then use join("\n", $arr) to convert array back to string. If you need to preserve separators, use preg_split as above with PREG_SPLIT_DELIM_CAPTURE option and skip delimiters when prepending strings.

If you used file() the line ends are already there, so use file_put_contents("newfile", join('', $arr)) to write it back.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜