Dean
Dean

Reputation: 763

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, alternate between T: and Z:.

Assume I use explode of some sort? Thanks

Upvotes: 2

Views: 2281

Answers (2)

shamittomar
shamittomar

Reputation: 46692

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);
?>

Upvotes: 3

StasM
StasM

Reputation: 11002

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.

Upvotes: 0

Related Questions