asdf
asdf

Reputation: 460

add a character to each line in a text file php

i'm a newbie and i have a text file.. the contents of the text file are as follows...

text1     text4     text7
text2     text5     text8
text3     text6     text9

what i want to do is add this --->>> character to every line in the first two vertical columns of the text file using php... how can i do this.... any help would be appreciated... thanks in advance... :).. i have tried the following code though...

<?php
$fileContents = file_get_contents('mytext.txt');
$fixedFileContents = "--->>>";
file_put_contents($fixedFileContents, 'mytext.txt');
?>

the output should look something like

--->>>text1     --->>>text4     text7
--->>>text2     --->>>text5     text8
--->>>text3     --->>>text6     text9

Upvotes: 3

Views: 2554

Answers (3)

h2ooooooo
h2ooooooo

Reputation: 39532

If I understand your question correctly, you can use preg_replace and regex for this:

$fileContents = preg_replace('/^(\w+\s+)(\w+\s+)/m', '--->>>$1--->>>$2', $fileContents);

Example:

<?php
    $fileContents = <<<TEXT
text1     text4     text7
text2     text5     text8
text3     text6     text9
TEXT;
    $fileContents = preg_replace('/^(\w+\s+)(\w+\s+)/m', '--->>>$1--->>>$2', $fileContents);
    echo $fileContents;
?>

Output:

--->>>text1     --->>>text4     text7
--->>>text2     --->>>text5     text8
--->>>text3     --->>>text6     text9

DEMO

Upvotes: 1

Joe
Joe

Reputation: 1394

What Marc B has said would work.

$file = file('file.txt');

$contents = null;

foreach($file as $line) {

   $line = preg_replace('/\s+/', ' --->>> ', $line);
   $contents .= '--->>> ' . $line . "\r\n";

}

file_put_contents('file.txt', $contents);

You could also use str_replace to remove the white space if you know the exact number of spaces, tabs or whitespace.

This should output something similar to the following:

--->>> test1   --->>> test4   --->>> test7
--->>> test2   --->>> test5   --->>> test8

Edit: Whoops, just noticed the exact thing I have was just posted! Ha! Edit 2: Added in replacement of white space to add the --->>> between values.

Upvotes: 1

Amal Murali
Amal Murali

Reputation: 76646

I'm not entirely sure what the output should be, but something like this should work:

$lines = file('mytext.txt'); 
$new = '';

if (is_array($lines)) {
    foreach($lines as $line) { 
        $new .= "--->>>" . $line;
    } 
}

file_put_contents('mytext.txt', $new);

Should give you:

--->>>text1     text4     text7
--->>>text2     text5     text8
--->>>text3     text6     text9

Upvotes: 2

Related Questions